You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Cloud API Gateway无法使用问题排查求助

问题分析

你遇到的UnknownHostException是因为Spring Cloud Gateway无法通过Eureka获取服务实例,转而尝试通过DNS解析自定义服务名(如DEPARTMENT-SERVICE),但DNS无法识别这类服务名,最终导致解析超时。核心原因有三点:

  1. 网关未配置Eureka客户端参数,无法连接Eureka服务器拉取服务列表
  2. 缺少Spring Cloud Loadbalancer依赖,无法处理lb://协议的负载均衡请求
  3. 部门服务的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

验证步骤

  1. 重启Eureka服务器、部门服务、用户服务和网关
  2. 访问Eureka控制台确认所有服务(包括API-GATEWAY)都已注册
  3. 通过网关端口9191访问API,比如http://localhost:9191/user/getUserDepartment/1,此时网关应能正确路由到对应服务

内容的提问来源于stack exchange,提问作者Thejas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 04:50:30