Spring cloud Gateway与nacos配置中心整合
新建工程并导入依赖
<!--gateway依赖,与spring-boot-start-web会有冲突,不可同时存在-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--注册服务到nacos-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--使用nacos的配置中心-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
修改配置文件 bootstrap.yml
server:
port: 10010
spring:
application:
name: gateway-service
profiles:
active: dev
cloud:
nacos:
discovery:
server-addr: localhost:8848
username: nacos
password: nacos
config:
server-addr: localhost:8848
file-extension: yaml
# 自动刷新配置文件
refresh-enabled: true
group: DEFAULT_GROUP
在nacos的配置中心新建配置文件,测试不同的谓词工厂
gateway-service-dev.yaml(命名格式必须为:服务名+特定环境配置文件名.yaml)
spring.cloud.gateway.routes:
- id: consumer
# lb 是 LoadBalancer的缩写,表示要使用本地的负载均衡器来路由到指定的服务
uri: lb://consumer-service
# 截取请求的第一个字段
filters:
- StripPrefix=1
# 1、The After Route Predicate Factory
predicates:
- After=2023-07-14T17:50:42.579+08:00[Asia/Shanghai]
# 2、The Before Route Predicate Factory
# predicates:
# - Before=2023-07-18T17:50:42.579+08:00[Asia/Shanghai]
# 3、The Between Route Predicate Factory
# predicates:
# - Between=2023-07-10T17:50:42.579+08:00[Asia/Shanghai],2023-07-18T17:50:42.579+08:00[Asia/Shanghai]
# 4、The Cookie Route Predicate Factory
# 设置访问请求的cookie名称和cookie值符合的正则表达式
# predicates:
# - Cookie=mycookie,[a-zA-Z]
# 5、The Header Route Predicate Factory
# 设置请求头的名称和请求头的值符合的正则表达式
# 只有请求的名称和设置一致并且请求头的值满足正则表达式,请求才能发送给服务
# predicates:
# - Header=Request-Id,[a-zA-Z]
# 6、The Host Route Predicate Factory
# 只有请求头的名称为host,并且符合**.somehost,请求才能转发给服务
# predicates:
# - Host=**.somehost
# 7、The Method Route Predicate Factory
# 设置能够访问的请求方法
# predicates:
# - Method=GET,POST
# 8、The Path Route Predicate Factory
# predicates:
# - Path=/consumer/**
# 9、The Query Route Predicate Factory
# 设置允许访问的携带参数的名称
# 只有请求携带有data的参数,请求才能访问到服务
# predicates:
# - Query=data
# 10、The RemoteAddr Route Predicate Factory
# 设置允许访问的ip地址
# 只有访问的ip地址在此网段内,请求才能访问服务
# predicates:
# - RemoteAddr=127.0.0.1/10