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

Spring Boot应用如何配置路由转发至Consul注册的po-ms服务?

解决方案

你只需要修改application.yml配置文件即可实现需求,无需编写额外代码或在Consul中操作,步骤如下:

1. 确保依赖已引入

如果你的项目还没添加Spring Cloud Gateway和Consul服务发现依赖,需要在对应构建文件中加入依赖:

  • Maven(pom.xml):
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
  • Gradle(build.gradle):
implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
implementation 'org.springframework.cloud:spring-cloud-starter-consul-discovery'

2. 修改application.yml配置

在原有配置基础上,添加Spring Cloud Gateway的路由配置:

server:  
  port: 8000
spring:
  application:
    name: "ai-gy"
  cloud:
    consul:
      discovery:
        enabled: true # 确保Consul服务发现功能开启
    gateway:
      routes:
        - id: po-ms-tran-route # 路由唯一标识,可自定义
          uri: lb://po-ms # 通过Consul服务发现调用po-ms服务,lb代表负载均衡
          predicates:
            - Path=/ai/tran/** # 匹配所有以/ai/tran开头的请求
          filters:
            - StripPrefix=1 # 移除请求路径中的第一个前缀段(即去掉ai,保留/tran/**转发到目标服务)

配置说明

  • uri: lb://po-ms:借助Spring Cloud负载均衡能力,自动从Consul中获取po-ms服务的实例地址(比如你提到的localhost:2222),无需硬编码端口。
  • Path=/ai/tran/**:指定触发该路由的请求路径规则。
  • StripPrefix=1:将请求路径中的第一个前缀部分(ai)移除,这样/ai/tran/1001就会被转发为/tran/1001到po-ms服务。

配置完成后重启应用,请求HTTP://localhost:8000/ai/tran/1001就会自动转发到po-ms服务的/tran/1001接口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 20:43:15