Gateway+Nacos 实现动态路由
Nacos的使用可以去nacos官网文档看下,这里主要介绍整合实现动态路由功能
一、Nacos环境准备
1)新增命名空间
命名空间ID默认生成或者自己填上都可以,这里直接默认生成了;
然后选择配置管理--配置列表--选中刚刚创建的命名空间--新增配置
然后点击右下角的发布
项目目录信息
consumer和producer代码是差不多的,就只贴producer的代码
@RestController
@RequestMapping("/provide/")
@Slf4j
public class ProviderController {
@GetMapping("/sayHello/{name}")
public String sayHello(@PathVariable("name") String name){
log.info("I'm calling nacos-provider service by dynamic gateway...");
return name + " Hi~, I'm from nacos-provider";
}
}
复制代码
spring:
application:
name: producer
cloud:
nacos:
username: nacos
password: nacos
discovery:
enabled: true
register-enabled: true
server-addr: localhost:8848
namespace: e863c93d-c8f5-47a9-bb7d-2e1eab762847
group: DEFAULT_GROUP
复制代码
server 模块,只需要在bootstrap.yml中加入配置信息就可以了
server:
port: 7000
spring:
application:
name: server
cloud:
gateway:
discovery:
locator:
# 是否与服务发现组件进行结合,通过 serviceId 转发到具体的微服务
enabled: true #是否开启基于服务发现得路由规则
nacos:
username: nacos
password: nacos
discovery:
enabled: true
register-enabled: true
server-addr: localhost:8848
namespace: e863c93d-c8f5-47a9-bb7d-2e1eab762847 # 命名空间
group: DEFAULT_GROUP # 读取配置的分组名称
config:
namespace: e863c93d-c8f5-47a9-bb7d-2e1eab762847
group: DEFAULT_GROUP
name: gateway.yaml # 配置的dataId
prefix: gateway # 配置的前缀
file-extension: yaml # 配置文件类型
refresh-enabled: true # 是否开启自动刷新
复制代码
在启动类上加上@EnableDiscoveryClient 注解,将微服务注册到服务发现组件上
然后分别启动
在浏览器中访问 http://localhost:7000/provide/sayHello/sss
然后在nacos中将配置信息修改为
spring:
cloud:
gateway:
routes:
- id: producer
uri: lb://producer
predicates:
- Path=/provide/**
- id: consumer
uri: lb://consumer
predicates:
- Path=/consume/**
复制代码
添加完过后直接访问 http://localhost:7000/consume/sayHello/sss