集成gateway网关。
1、在父模块中创建子模块springboot项目
2、导入maven相关依赖
<!-- 服务注册与发现-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- 网关-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- 响应式编程-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
3、在主启动类上方增加注解@EnableDiscoveryClient
启动nacos服务发现
4、编写网关配置文件(包含请求校验规则)
示例配置(附注释)
spring:
cloud:
nacos:
discovery:
server-addr: 192.168.1.3:8086
gateway:
discovery:
locator:
include-expression: "*"
routes:
# 设置路由id,必须唯一
- id: after_route
# 设置映射地址,lb://服务名->http://服务名对应的ip地址:端口号
uri: lb://customer
# 配置校验请求网关的地址是否符合要求
predicates:
# 路径校验(/**放开所有)
- Path=/**
- id: test_route
# 设置映射地址,lb://服务名->http://服务名对应的ip地址:端口号
uri: lb://provider
# 配置校验请求网关的地址是否符合要求
predicates:
# 路径校验(/**放开所有)
- Path=/test/**
## 请求方式只能为get请求
# - Method=GET
## 请求参数必须包含green,逗号后为正则表达式,表示检验值的规则 如:http:localhost:5656/test?green=ccca
# - Query=green,ccc.
## 在该时间之后
# - After=2020-01-20T17:42:47.789-07:00[America/Denver]
## 在该时间之前
# - Before=2017-01-20T17:42:47.789-07:00[America/Denver]
## 时间段匹配,在以下时间请求会匹配该路由
# - Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]
## 通过cookie的键值匹配,值支持正则表达式
# - Cookie=aa,bb
## 请求头匹配 值支持正则表达式
# - Header=X-Request-Id, \d+
## 主机匹配
# - Host=**.com,**.com
## ip地址匹配
# - RemoteAddr=192.168.1.1/24
## 权重匹配,如果有多个路由匹配,通过权重选择
# - Weight=group1, 2
## 可以二次处理请求路径
# filters:
## 匹配后自动在路径前添加前缀
# - PrefixPath=/a
## 匹配后去点路径前缀n个 如:http:localhost:8080/a/b/c 则变为 http:localhost:8080/b/c
# - StripPrefix=1
## 删除请求参数
# - RemoveRequestParameter=red
## 设置路径
# - SetPath=/{segment}
## 设置请求头
# - SetRequestHeader=foo, bar-{segment}
## 重定向
# - RedirectTo=302, https://acme.org
# args:
## 重试请求
# retries: 3
## 请求状态
# statuses: BAD_GATEWAY
## 请求方法
# methods: GET,POST
# backoff:
# firstBackoff: 10ms
# maxBackoff: 50ms
# factor: 2
# basedOnPreviousValue: false
## 请求大小限制
# maxSize: 5000000
application:
name: gateWay-nacos
management:
endpoint:
gateway:
enabled: true
server:
port: 5656
測試
我们网关的端口是5656
网关是所有请求的入口,我们请求网关的服务,看看是否转发到对应服务名的请求接口。
成功,以上内容为消费者对应的接口返回。
集成配置中心
1、在父模块中创建子模块springboot项目
2、导入maven相关依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
3、进入nacos注册中心控制台新增配置中心
配置案例如图
dataId需要与应用名称对应
4、创建bootstrap.yml
文件并配置
启用配置中心并配置配置中心的地址
应用名称需要对应nacos配置中心的dataid
yml配置如下:
spring:
cloud:
nacos:
config:
server-addr: 192.168.1.3:8086
enabled: true
file-extension: yml
# 应用名称需要对应nacos配置中心的dataid,他会使用对应的配置中心的配置
application:
name: aConfig
可以在你用到配置文件的类上可以使用注解
@RefreshScope
,支持实时刷新。配置中心修改会同步修改
接口如图,集成配置中心测试。
测试成功。配置中心集成hello world完成!
结语
欢迎大家讨论交流❤️❤️❤️
扫描二维码关注公众号,回复:
13714558 查看本文章