企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
实现动态路由需要注册中心的支持,这里选择Eureka作为注册中心。注册中心模块 cloud-eureka-server7001 已经提前搭建好了,课件代码中有提供。 <br/> 默认情况下Gateway会<mark>根据注册中心注册的服务列表,以注册中心上微服务名为路径创建动态路由进行转发,从而实现动态路由的功能</mark>,这样就不用写死一个地址了。 <br/> 动态路由实现步骤如下: **1. 在网关模块 cloud-gateway-gateway9527 新增 eureka-client 依赖** ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> ``` **2. 在网关模块的`application.yml`中配置路由规则** ```yml spring: application: name: cloud-gateway-service cloud: gateway: routes: - id: payment_routh #uri: http://localhost:8001 #匹配后提供服务的路由地址 uri: lb://cloud-payment-service #动态路由后写成服务端的 sping.application.name 配置 predicates: - Path=/payment/get/** #断言,路径相匹配的进行路由 - id: payment_routh2 #uri: http://localhost:8002 uri: lb://cloud-payment-service predicates: - Path=/payment/lb/** discovery: locator: enabled: true #开启从注册中心动态生成路由的功能,用微服务名进行路由 eureka: client: service-url: defaultZone: http://localhost:7001/eureka/ #当前模块注册到Eureka ``` **3. 不要忘记在网关模块的启动类上标记Eureka的注解`@EnableEurekaClient`** ```java @SpringBootApplication @EnableEurekaClient public class GateWayMain9527 { public static void main(String[] args) { SpringApplication.run(GateWayMain9527.class, args); } } ``` **4. 测试** (1)启动注册中心 cloud-eureka-server7001、服务端模块 cloud-provider-payment8001、服务端模块 cloud-provider-payment8002、网关模块 cloud-gateway-gateway9527。 (2)通过网关模块 9527 访问 8001、8002 模块:http://localhost:9527/payment/get/nameone/zhangsan 。 :-: ![](https://img.kancloud.cn/1e/18/1e18a5ed2e0ad6748e345c353cc72879_918x164.gif) 不停刷新,可以看到在 8001、8002 直接切换。