原因是RouteToRequestUrlFilter里面改了GATEWAY_ROUTE_ATTR的值,NettyRoutingFilter执行时候就按照这个了
这个问题真tm坑啊,后续还是好好分析下,springcloudgateway肯定是gloabfilter干的这事情啊
下面这段话是引用别人的
在网关中经常有这样的需求,客户端访问网址"http://a.com/hello",网关将请求转发到"http://b.com/world"。
按照Spring的官方文档http://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.0.0.RELEASE/multi/multi__developer_guide.html#_writing_custom_gatewayfilter_factories,在PreGatewayFilterFactory中,修改ServerHttpRequest的uri,发现请求路径是变了,但是域名并没有生效,请求依然被转发到声明Route时的uri。
原因:
将Gateway日志设置为debug模式:logging.level.org.springframework.cloud.gateway=debug,请求filter时控制台打印日志:
2018-06-2715:37:41.208DEBUG93609--- [ctor-http-nio-3] o.s.c.g.handler.FilteringWebHandler : SortedgatewayFilterFactories:[OrderedGatewayFilter{delegate=GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.AdaptCachedBodyGlobalFilter@53aa2fc9}, order=-2147482648}, OrderedGatewayFilter{delegate=GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.NettyWriteResponseFilter@69364b2d}, order=-1}, OrderedGatewayFilter{delegate=GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.ForwardPathFilter@ea00de}, order=0}, OrderedGatewayFilter{delegate=com.example.cloud.filter.previous.PreviousFilterFactory$$Lambda$412/104912388@4127cf4b, order=1}, OrderedGatewayFilter{delegate=GatewayFilterAdapter{delegate=com.example.cloud.filter.AuthFilter@6f9ab79d}, order=100}, OrderedGatewayFilter{delegate=GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter@4792f119}, order=10000}, OrderedGatewayFilter{delegate=GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.LoadBalancerClientFilter@64ae105d}, order=10100}, OrderedGatewayFilter{delegate=GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.WebsocketRoutingFilter@23ca36d}, order=2147483646}, OrderedGatewayFilter{delegate=GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.NettyRoutingFilter@10a18e3e}, order=2147483647}, OrderedGatewayFilter{delegate=GatewayFilterAdapter{delegate=org.springframework.cloud.gateway.filter.ForwardRoutingFilter@5bde57ab}, order=2147483647}]
查看源码org.springframework.cloud.gateway.filter.NettyRoutingFilter,发现httpClient请求的url是通过exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);获取的。我们在自定义的Filter中设置目标uri:exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, targetUri); 发现并没有生效。
继续查看源码org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter,发现Spring Gateway在这个全局Filter中使用声明Route时的Uri覆盖了上面我们自己制定的GATEWAY_REQUEST_URL_ATTR。
解决:
找到问题出在Route中,我们只要在自定义的Filter中重新设置Route的Uri即可。
再次访问,已经正确跳转到我们指定的uri。