spring-cloud-gateway统一前缀

由于前端框架需要做路由代理,需要在后端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
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值