Spring Cloud Gateway中lb://格式路由的测试方案求助
Spring Cloud Gateway lb路由测试(无Eureka)解决503问题
在SpringBootTest环境中测试lb://协议路由时出现503,大概率是自定义的服务实例提供者没有被负载均衡器正确关联,或者缺少必要依赖。以下是可直接复用的测试方案:
关键前提
确保项目引入spring-cloud-starter-loadbalancer依赖,Spring Cloud Gateway从2020.0版本开始需要该依赖来处理负载均衡路由,缺失会导致lb协议无法解析,直接返回503。
完整测试示例
1. 测试类配置
@LoadBalancerClient(name = "mock-service", configuration = MockServiceInstanceConfig.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc public class GatewayLbRouteTest { @Autowired private MockMvc mockMvc; @Autowired private WireMockServer wireMockServer; // 自定义服务实例提供者配置 @TestConfiguration static class MockServiceInstanceConfig { @Bean public ServiceInstanceListSupplier serviceInstanceListSupplier() { // 构造Mock服务实例,指向WireMock端口 ServiceInstance mockInstance = new DefaultServiceInstance( "mock-service-1", "mock-service", "localhost", wireMockServer.port(), false ); // 使用Spring提供的静态实例列表提供者,替代自定义匿名实现 return new StaticServiceInstanceListSupplier(List.of(mockInstance)); } } @Test void testLbRouteForward() throws Exception { // 配置WireMock返回模拟响应 wireMockServer.stubFor(get("/api/test") .willReturn(aResponse() .withStatus(200) .withBody("Mock Service Response"))); // 调用Gateway路由,假设路由配置为/lb/** 转发到 lb://mock-service/api/** mockMvc.perform(get("/lb/test")) .andExpect(status().isOk()) .andExpect(content().string("Mock Service Response")); } }
2. Gateway路由配置(application-test.yml)
spring: cloud: gateway: routes: - id: mock-service-route uri: lb://mock-service predicates: - Path=/lb/** filters: - RewritePath=/lb/(?<path>.*), /api/$\{path}
问题分析(针对你之前的配置)
- 未绑定服务ID:自定义的
ServiceInstanceListSupplier没有通过@LoadBalancerClient和mock-service关联,导致负载均衡器无法识别该实例列表对应哪个服务。 - 依赖缺失:如果没有引入
spring-cloud-starter-loadbalancer,Gateway无法处理lb://协议,直接返回503。 - 实现冗余:无需手动实现
ServiceInstanceListSupplier匿名类,Spring提供的StaticServiceInstanceListSupplier更简洁且不易出错。
内容的提问来源于stack exchange,提问作者hk02
相关产品推荐
相关产品推荐

