原因是RouteToRequestUrlFilter里面改了GATEWAY_ROUTE_ATTR的值,NettyRoutingFilter執(zhí)行時候就按照這個了
這個問題真tm坑啊,后續(xù)還是好好分析下,springcloudgateway肯定是gloabfilter干的這事情啊
下面這段話是引用別人的
在網(wǎng)關(guān)中經(jīng)常有這樣的需求,客戶端訪問網(wǎng)址"http://a.com/hello",網(wǎng)關(guān)將請求轉(zhuǎn)發(fā)到"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,發(fā)現(xiàn)請求路徑是變了客峭,但是域名并沒有生效豫领,請求依然被轉(zhuǎn)發(fā)到聲明Route時的uri。
原因:
將Gateway日志設(shè)置為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等恐,發(fā)現(xiàn)httpClient請求的url是通過exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);獲取的。我們在自定義的Filter中設(shè)置目標(biāo)uri:exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, targetUri); 發(fā)現(xiàn)并沒有生效备蚓。
繼續(xù)查看源碼org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter课蔬,發(fā)現(xiàn)Spring Gateway在這個全局Filter中使用聲明Route時的Uri覆蓋了上面我們自己制定的GATEWAY_REQUEST_URL_ATTR。
解決:
找到問題出在Route中郊尝,我們只要在自定義的Filter中重新設(shè)置Route的Uri即可二跋。
再次訪問,已經(jīng)正確跳轉(zhuǎn)到我們指定的uri流昏。