spring cloud gateway 功能:
添加依赖:不能添加web的starter
org.springframework.cloud spring-cloud-starter-gateway
基本用法两种:
@BeanRouteLocator routeLocator(RouteLocatorBuilder builder){return builder.routes()// route的名字.route("cc_route",r->r.path("/get").uri("http://httpbin.org")).build();}
spring:application:# 服务名字name: gatewaycloud:gateway:routes:- id: cc_routeuri: http://httpbin.org/predicates:- Path=/get
server:port: 8080
eureka:client:service-url:# 注册地址defaultZone: http://localhost:1111/eureka
注册到eureka上:
spring:application:# 服务名字name: gatewaycloud:gateway:# routes:
# - id: cc_route
# uri: http://httpbin.org/
# predicates:
# - Path=/getdiscovery:locator:# 是否开启通过 注册中心 进行路由转发 的功能,,,,。。。。开启自动代理enabled: trueserver:port: 8080
eureka:client:service-url:# 注册地址defaultZone: http://localhost:1111/eurekalogging:level:com:cj:gateway: debug
开启自动代理
spring.cloud.gateway.discovery.locator.enabled=true
访问http://localhost:8080/PROVIDER/hello :主机地址+服务名字+接口 ,,provider注册到Eureka是大写
多种匹配方式可以组合使用
spring:application:# 服务名字name: gatewaycloud:gateway:routes:- id: cc_routeuri: http://httpbin.orgpredicates:# 在这个日期之后,, 才转发
# - After=2021-12-08T21:00:00+08:00[Asia/Shanghai]# 在这个日期之前- Before=2023-12-08T21:00:00+08:00[Asia/Shanghai]# 两个日期之间,,用 逗号 分隔
# - Between- Method=GET# 相当于 访问http://httpbin.org/get- Path=/get# 相当于 访问http://httpbin.org/hehe/占位符segment
# - Path=/hehe/{segment}# 请求中 一定要有 name参数才会转发
# - Query=name# 请求中 一定要有name参数,,并且value是以java开头- Query=name,java.*discovery:locator:# 是否开启通过 注册中心 进行路由转发 的功能,,,,。。。。开启自动代理enabled: true
routes规则可以有多个,,如果被多个匹配上,,首先会采用第一个的方式进行转发
分为两大类:
使用AddRequestParameter 过滤器: 在请求转发路由的时候,,自动携带上参数
spring:application:# 服务名字name: gatewaycloud:gateway:routes:- id: cc_route# lb: load balance : 负载均衡,,, 这次访问直接 localhost:8080/hello2 ,,,所有的请求都会直接跳转到 lb://provideruri: lb://providerfilters:# 给 provider 的 接口添加参数 name,,值为value- AddRequestParameter=name,hehepredicates:# 在这个日期之后,, 才转发
# - After=2021-12-08T21:00:00+08:00[Asia/Shanghai]# 在这个日期之前- Before=2023-12-08T21:00:00+08:00[Asia/Shanghai]# 两个日期之间,,用 逗号 分隔
# - Between- Method=GETdiscovery:locator:# 是否开启通过 注册中心 进行路由转发 的功能,,,,。。。。开启自动代理enabled: true