关于 Spring Cloud,需要学习的知识点非常多,本篇是学习 Spring Cloud Gateway (以下简称为 Gateway)时一些知识点的汇总,主要围绕着配置文件 ruoyi-gateway.yml 展开。
ruoyi-gateway.yml

官方文档说明:
《Spring Cloud微服务和分布式系统实战》说明:
以第一个路由配置为例进行说明:
spring:
cloud:
# 网关配置
gateway:
# 打印请求日志(自定义)
requestLog: true
discovery:
locator:
# 断言和过滤器使用小写服务id
lowerCaseServiceId: true
# 开启从注册中心动态创建路由的功能
enabled: true
routes:
# 认证中心
# 路由的ID,没有固定规则但要求唯一,建议配合服务名
- id: ruoyi-auth
# 匹配后的目标服务地址,供服务的路由地址
# 需要注意的是 uri 的协议为 lb,表示启用 Gateway 的负载均衡功能。
# lb://serviceName 是 spring cloud gateway 在微服务中自动为我们创建的负载均衡 uri
uri: lb://ruoyi-auth
# 断言
predicates:
# 路径相匹配的进行路由
- Path=/auth/**
filters:
# 验证码处理
- ValidateCodeFilter
# StripPrefixGatewayFilterFactory
# 此过滤器在将请求发送到下游之前从请求中删除路径的第一部分(称为前缀)。
- StripPrefix=1
spring.cloud.gateway.discovery.locator.enabled=true

spring.cloud.gateway.discovery.locator.lowerCaseServiceId=true

lbspring.cloud.gateway.routes[0].uri=lb://ruoyi-auth
uri 参数可以直接填写具体路径,如:http://localhost:8080/ruoyi-auth,这里使用 lb 表示启用负载均衡功能:

spring.cloud.gateway.routes[0].predicates=[Path=/auth/**]
关于断言,一共有 12 种断言工厂:
Path 路由断言配置:
Path 路由断言相对简单,只需要匹配相关路径即可。
PathRoutePredicateFactory#apply

spring.cloud.gateway.routes[0].filters=[StripPrefix=1]
过滤器种类非常多,默认有 34 种:
去掉第一个前缀:
StripPrefixGatewayFilterFactory#apply

(完)