Spring Cloud API Gateway无法使用问题排查求助
问题分析
你遇到的UnknownHostException是因为Spring Cloud Gateway无法通过Eureka获取服务实例,转而尝试通过DNS解析自定义服务名(如DEPARTMENT-SERVICE),但DNS无法识别这类服务名,最终导致解析超时。核心原因有三点:
- 网关未配置Eureka客户端参数,无法连接Eureka服务器拉取服务列表
- 缺少Spring Cloud Loadbalancer依赖,无法处理
lb://协议的负载均衡请求 - 部门服务的Eureka配置存在拼写错误,可能导致服务注册异常
解决方案
1. 给网关补充Eureka客户端配置
在网关的application.yml中添加Eureka连接配置,让网关能注册到Eureka并获取服务实例:
server: port: 9191 spring: application: name: API-GATEWAY cloud: gateway: routes: - id: DEPARTMENT-SERVICE uri: lb://DEPARTMENT-SERVICE predicates: - Path=/departments/** - id: USER-SERVICE uri: lb://USER-SERVICE predicates: - Path=/user/** # 新增Eureka客户端配置 eureka: client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:8761/eureka/ instance: prefer-ip-address: true
2. 给网关添加Spring Cloud Loadbalancer依赖
Spring Cloud 2021版本(你使用的2021.0.3)已弃用Ribbon,默认使用Spring Cloud Loadbalancer处理负载均衡。在网关的pom.xml中添加该依赖:
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!-- 新增Loadbalancer依赖 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-loadbalancer</artifactId> </dependency> </dependencies>
3. 修正部门服务的Eureka配置拼写错误
你的DepartmentService中register-witheureka拼写错误,正确参数名是register-with-eureka(带连字符),修正后的application.yml:
server: port: 9001 spring: application: name: DEPARTMENT-SERVICE eureka: client: # 修正拼写错误 register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:8761/eureka/ instance: hostname: localhost prefer-ip-address: true
验证步骤
- 重启Eureka服务器、部门服务、用户服务和网关
- 访问Eureka控制台确认所有服务(包括
API-GATEWAY)都已注册 - 通过网关端口
9191访问API,比如http://localhost:9191/user/getUserDepartment/1,此时网关应能正确路由到对应服务
内容的提问来源于stack exchange,提问作者Thejas
相关产品推荐
相关产品推荐

