由于前端框架需要做路由代理,需要在后端api接口加上前缀,区分前端路由跟后端接口。前后端分离项目,后端采用Spring cloud微服务架构。

一、第一次尝试(失败)
在spring-cloud-gateway的配置文件中直接加入应用的上下文路径(项目访问路径)

server:
servlet:
context-path: /api
在原有接口上增加“/api*“请求,请求不到相应的接口。

二、深入学习spring-cloud-gateway的url处理方式
1、理解spring-cloud-gateway
在Spring官网上有spring-cloud-gateway功能流程介绍图,如下图:

image
客户端向spring-cloud-getway发出请求,如果网关处理程序映射确定请求与配置路由匹配,则将其发送给网关Web,web处理程序通过特定于请求的过滤器运行请求,过滤器被虚线分割的原因是过滤器可在发送代理请求之前和之后进行逻辑运算。执行所有的过滤器逻辑。最后发送代理请求,相应的微服务执行客户端发送的请求。

2、The PrefixPath GatewayFilter Factory(前缀路径网关过滤器工厂)
设置网关前缀:

spring:
cloud:
gateway:
routes:
- id: prefixpath_route
uri: https://example.org
filters:
- PrefixPath=/mypath
This will prefix /mypath to the path of all matching requests. So a request to /hello would be sent to /mypath/hello.

这将为所有匹配请求的路径加上前缀/mypath。因此,/hello的请求将使用到/mypath/hello。

3、The StripPrefix GatewayFilter Factory(带前缀的网关过滤工厂)
设置网关前缀:

spring:
cloud:
gateway:
routes:
- id: nameRoot
uri: https://nameservice
predicates:
- Path=/name/**
filters:
- StripPrefix=2
When a request is made through the gateway to /name/blue/red, the request made to nameservice looks like nameservice/red.

当通过网关向/name/blue/red发出请求时,向nameservice发出的请求看起来就像nameservice/red。

总结:
在第2种方法与第3种方法选用一种就行。

作者:程序者王大川
链接:https://www.jianshu.com/p/324372192a26
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐