Docker + Nacos + Spring Cloud Gateway 实现简单的动态路由配置修改和动态路由发现
以下是一个简化的示例,展示如何使用Docker、Nacos和Spring Cloud Gateway实现简单的动态路由配置和动态路由广播。
- 创建
pom.xml
,包含Spring Cloud Gateway和Nacos依赖:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
- 配置文件
application.yml
:
spring:
cloud:
gateway:
discovery:
locator:
enabled: true # 开启基于服务发现的路由
routes:
- id: user-service
uri: lb://user-service # 用户服务的URI
predicates:
- Path=/user/**
- id: order-service
uri: lb://order-service # 订单服务的URI
predicates:
- Path=/order/**
server:
port: 8080
spring:
application:
name: gateway-service
management:
endpoints:
web:
exposure:
include: "*"
# Nacos 服务注册与发现配置
spring.cloud.nacos.discovery.server-addr: 127.0.0.1:8848
- 启动类
GatewayApplication.java
:
@SpringBootApplication
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
- 使用Docker Compose来定义和运行Docker容器,
docker-compose.yml
:
version: '3'
services:
nacos:
image: nacos/nacos-server
environment:
- MODE=standalone
ports:
- "8848:8848"
gateway-se
评论已关闭