Spring cloud gateway setting context-path service routing 404 troubleshooting

1. Background

    Recently, the gateway was restructured. The technology was selected as spring cloud gateway. Consul was used as the configuration center and registration center. It adhered to the principle of non-restart. The gateway implements a dynamic routing mechanism and uses timed tasks to update the gateway routing information regularly.

 

2. Service Information

   Microservice gateway: spring-cloud-gateway

   Microservices: order-service, user-service

 

3. Problem description

   Because the gateway service integrates knife4j, you can access the knife4j information of all services in the same registry by visiting http://gatewayip:port/doc.html, but the user service-related interface reports a 404 error when actually visiting .

 

Four, troubleshooting

  1. The investigation found that the order-service did not set server.servlet.context-path, and the user-service was set;

  2. Verify the influence of context-path and find that the path field value must be prefixed and intercepted when routing is set to allow normal routing;

  3. Since the company gateway is an existing product, the current technical framework is refactored, so the original interface access path cannot be changed, so no prefix can be added in front of the original path;

  Check the source code and find that the request will go through

FilteringWebHandler的
filter方法,此方法

In the routing process, there will be 12 filters, of which the fifth filter

RewritePathGatewayFilterFactory中的
apply方法会匹配服务启动时加载的
regexp正则,从而对服务path进行改写。

The source code is as follows:

 

Five, the solution

1) If the configured routing URI is lb, the registry service name cannot be the same as the server.servlet.context-path name, otherwise the contextPath will be rewritten to an empty string;

2) If the registry and server.servlet.context-path must be the same, when setting the Path in the assertion, a prefix must be wrapped before the contextPath, and the first string must be intercepted in the Filter;

3) The gateway is forbidden to actively pull routing information from consul and set the default filter. This operation will set the default filter rule, and the reWritePath matching regular will modify the request path

      Add a comment to the startup class:

     

 @SpringBootApplication( exclude = org.springframework.cloud.gateway.discovery.GatewayDiscoveryClientAutoConfiguration.class) 

4) Recommended

   Rewrite the filter chain (just add the following configuration):

   

spring.cloud.gateway.discovery.locator.filters[0]=PreserveHostHeader

 

Guess you like

Origin blog.csdn.net/weixin_39195030/article/details/106720083