目录
1.新建Module cloud-gateway-gateway9527
💧ReadBodyPredicateFactory Route Predicate
🐟AddRequestParameter GatewayFilter Factory
🐟 AddRequestHeader GatewayFilter Factory
🐟 AddResponseHeader GatewayFilter Factory
🐟DedupeResponseHeader GatewayFilter Factory
上一代zuul 1.X:Home · Netflix/zuul Wiki · GitHub
gateway的官网:Spring Cloud Gateway


Spring Cloud Gateway 具有如下特性:
基于Spring Framework 5, Project Reactor 和 Spring Boot 2.0 进行构建;
动态路由:能够匹配任何请求属性;
可以对路由指定 Predicate(断言)和 Filter(过滤器);
集成Hystrix的断路器功能;
集成 Spring Cloud 服务发现功能;
易于编写的 Predicate(断言)和 Filter(过滤器);
请求限流功能;
支持路径重写。
Spring Cloud Gateway 与 Zuul的区别
在SpringCloud Finchley正式版之前,Spring Cloud 推荐的网关是 Netflix 提供的Zuul:
Springcloud中所集成的Zuul版本,采用的是Tomcat容器,使用的是传统的Servlet IO处理模型。
🐟Servlet的生命周期?
- servlet由servlet container进行生命周期管理。
- container启动时构造servlet对象并调用servlet init()进行初始化;
- container运行时接受请求,并为每个请求分配一个线程(一般从线程池中获取空闲线程)然后调用service()。
- container关闭时调用servlet destory()销毁servlet

上述模式的缺点:
💧💧💧💧💧什么是webflux


路由是构建网关的基本模块,它由ID,目标URI,一系列的断言和过滤器组成
如果断言为true则匹配该路由
参考的是Java8的java.util.function.Predicate
指的是Spring框架中GatewayFilter的实例,使用过滤器,可以在请求被路由前或者之后对请求进行修改。



客户端向 Spring Cloud Gateway 发出请求。
然后在 Gateway Handler Mapping 中找到与请求相匹配的路由,将其发送到 Gateway Web Handler。
Handler 再通过指定的过滤器链来将请求发送到我们实际的服务执行业务逻辑,然后返回。
过滤器之间用虚线分开是因为过滤器可能会在发送代理请求之前(“pre”)或之后(“post”)执行业务逻辑。
路由转发+执行过滤器链

- "1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <parent>
- <artifactId>cloud2022artifactId>
- <groupId>com.atxupt.springcloudgroupId>
- <version>1.0-SNAPSHOTversion>
- parent>
- <modelVersion>4.0.0modelVersion>
-
- <artifactId>cloud-gateway-gateway9527artifactId>
-
- <properties>
- <maven.compiler.source>8maven.compiler.source>
- <maven.compiler.target>8maven.compiler.target>
- properties>
- <dependencies>
-
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-gatewayartifactId>
- dependency>
-
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
- dependency>
-
- <dependency>
- <groupId>com.atxupt.springcloudgroupId>
- <artifactId>cloud-api-commonsartifactId>
- <version>${project.version}version>
- dependency>
-
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-devtoolsartifactId>
- <scope>runtimescope>
- <optional>trueoptional>
- dependency>
- <dependency>
- <groupId>org.projectlombokgroupId>
- <artifactId>lombokartifactId>
- <optional>trueoptional>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-testartifactId>
- <scope>testscope>
- dependency>
- dependencies>
-
- project>

- @SpringBootApplication
- @EnableEurekaClient
- public class GateWay9527 {
- public static void main(String[] args) {
- SpringApplication.run(GateWay9527.class,args);
- }
- }


- server:
- port: 9527
-
- spring:
- application:
- name: cloud-gateway
- cloud:
- gateway:
- routes:
- - id: payment_routh #payment_route #路由的ID,没有固定规则但要求唯一,建议配合服务名
- uri: http://localhost:8001 #匹配后提供服务的路由地址
- predicates:
- - Path=/payment/get/** # 断言,路径相匹配的进行路由
-
- - id: payment_routh2 #payment_route #路由的ID,没有固定规则但要求唯一,建议配合服务名
- uri: http://localhost:8001 #匹配后提供服务的路由地址
- predicates:
- - Path=/payment/lb/** # 断言,路径相匹配的进行路由
-
- eureka:
- instance:
- hostname: cloud-gateway-service
- client: #服务提供者provider注册进eureka服务列表内
- service-url:
- register-with-eureka: true
- fetch-registry: true
- defaultZone: http://eureka7001.com:7001/eureka







按照上面的步骤完成
Ⅰ、官网的案例

Ⅱ、百度国内新闻网址,需要外网

Ⅲ、自己写一个
新建配置类GateWayConfig

- @Configuration
- public class GateWayConfig {
- @Bean
- public RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder){
- RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();
- //http://news.baidu.com/guonei
- //当访问地址 http://localhost:9527/guonei时会自动转发到地址:
- //http://news.baidu.com/guonei
-
- routes.route(
- "path_route_atxupt",
- r -> r.path("/guonei").uri("http://news.baidu.com/guonei")).build();
-
- return routes.build();
- }
- }
最终效果

存在的问题:地址写死啦

默认情况下Gateway会根据注册中心注册的服务列表,以注册中心上微服务名为路径创建动态路由进行转发,从而实现动态路由的功能
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
- dependency>
- server:
- port: 9527
-
- spring:
- application:
- name: cloud-gateway
- cloud:
- gateway:
- discovery:
- locator:
- enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由
- routes:
- - id: payment_routh #payment_route #路由的ID,没有固定规则但要求唯一,建议配合服务名
- # uri: http://localhost:8001 #匹配后提供服务的路由地址
- uri: lb://cloud-payment-service #匹配后提供服务的路由地址
- predicates:
- - Path=/payment/get/** # 断言,路径相匹配的进行路由
-
- - id: payment_routh2 #payment_route #路由的ID,没有固定规则但要求唯一,建议配合服务名
- # uri: http://localhost:8001 #匹配后提供服务的路由地址
- uri: lb://cloud-payment-service #匹配后提供服务的路由地址
- predicates:
- - Path=/payment/lb/** # 断言,路径相匹配的进行路由
-
- eureka:
- instance:
- hostname: cloud-gateway-service
- client: #服务提供者provider注册进eureka服务列表内
- service-url:
- register-with-eureka: true
- fetch-registry: true
- defaultZone: http://eureka7001.com:7001/eureka
启功gateway9527时


说白了,Predicate就是为了实现一组匹配规则,让请求过来找到对应的Route进行处理。


After断言有一个参数,一个datetime(其是Java ZonedDateTime)。该断言匹配在指定日期时间之后发生的请求(如果没到时间,就会报404错误)。下面的示例配置路由后断言
- spring:
- cloud:
- gateway:
- routes:
- - id: after_route
- uri: https://example.org
- predicates:
- - After=2019-01-20T17:42:47.789-07:00[America/Denver]
Before断言有一个参数,一个datetime(其是Java ZonedDateTime)。该断言匹配在指定之前发生的请求datetime。以下示例配置了路由前断言

- spring:
- cloud:
- gateway:
- routes:
- - id: before_route
- uri: https://example.org
- predicates:
- - Before=2022-12-30T17:20:00.789-07:00[America/Denver]
Between Route Predicate Factory 中获取一个UTC时间格式的参数, 当请求的当前时间在配置的UTC时间之间,则会成功匹配,否则不能成功匹配。
- spring:
- cloud:
- gateway:
- routes:
- - id: between_route
- uri: https://example.org
- predicates:
- - Between=2022-12-30T17:20:00.789-07:00[America/Denver], 2019-01-21T17:42:47.789-07:00[America/Denver]
- spring:
- cloud:
- gateway:
- routes:
- - id: cookie_route
- uri: https://example.org
- predicates:
- - Cookie=chocolate, ch.p
Header Route Predicate Factory 根据配置的路由Header信息进行断言匹配路由,匹配成功进行转发,否则不进行转发。
- spring:
- cloud:
- gateway:
- routes:
- - id: header_route
- uri: https://example.org
- predicates:
- - Header=X-Request-Id, \d+
Host Route Predicate Factory 根据配置的Host,对请求中的Host进行断言处理,断言匹配成功进行转发,否则不进行转发。
- spring:
- cloud:
- gateway:
- routes:
- - id: host_route
- uri: https://example.org
- predicates:
- - Host=**.somehost.org,**.anotherhost.org
Method Route Predicate Factory 根据路由信息配置的Method对请求方式是Get或者Post等进行断言匹配,断言匹配成功进行转发,否则不进行转发
- spring:
- cloud:
- gateway:
- routes:
- - id: method_route
- uri: https://example.org
- predicates:
- - Method=GET
Path Route Predicate Factory 基于Spring PathMatcher 模式的路径匹配路由
- application.yml
- spring:
- cloud:
- gateway:
- routes:
- - id: host_route
- uri: https://example.org
- predicates:
- - Path=/foo/{segment},/bar/{segment}
Query Route Predicate Factory 根据请求中的两个参数进行断言匹配,断言匹配成功进行转发,否则不进行转发。
- spring:
- cloud:
- gateway:
- routes:
- - id: query_route
- uri: https://example.org
- predicates:
- - Query=foo,baz
WeightAddrRoutePredicate由group和weight(权重数值)组成,表示将相同的请求根据权重跳转到不同的uri地址,要求group的名称必须一致,配置如下
- spring:
- cloud:
- gateway:
- routes:
- - id: weight_high
- uri: https://weighthigh.org
- predicates:
- - Weight=groupName, 8
- - id: weight_low
- uri: https://weightlow.org
- predicates:
- - Weight=groupName, 2
SCG自带ReadBodyPredicateFactory断言,可以将body中的内容读取到exchange对象中,使用exchange.getAttribute("cachedRequestBodyObject")获取
但是当body为空时,无法匹配该路由,导致返回404错误。
- - id: r_fapi #测试
- uri: lb://LIZZ-GATEWAY
- predicates:
- - Path=/fapi/**
- - name: ReadBodyPredicateFactory #读取body断言
- args:
- inClass: "#{T(String)}" #body数据类型
- predicate: "#{@testRequestBody}" #自定义断言处理器
RemoteAddr Route Predicate Factory 配置一个IPv4或者IPv6网段的字符串或者IP。当请求IP地址在网段之内或者和配置的IP相同,断言匹配成功进行转发,否则不进行转发。

(业务逻辑之前和业务逻辑之后)

Ⅰ、GatewayFilter (单一)

Ⅱ、GlobalFilter(全局)

输入两个参数:Request Query Name、Value,向下游请求地址添加 URL 参数信息
- server:
- port: 9588
-
- spring:
- application:
- name: cloud-gateway
- cloud:
- gateway:
- discovery:
- locator:
- enabled: true #开启从注册中心动态创建路由的功能
- lower-case-service-id: true #使用小写服务名,默认是大写
- routes:
- - id: payment_routh #payment_route #路由的ID,没有固定规则但要求唯一,建议配合服务名
- uri: lb://cloud-provider-payment #匹配后的目标服务地址,供服务的路由地址
- #uri: http://localhost:8001 #匹配后提供服务的路由地址
- filters:
- - AddRequestParameter=X-Request-Id,1024 #过滤器工厂会在匹配的请求头加上一对请求头,名称为X-Request-Id值为1024
- predicates:
- - Path=/paymentInfo/** # 断言,路径相匹配的进行路由
- - Method=GET,POST
-
- eureka:
- instance:
- hostname: cloud-gateway-service
- client: #服务提供者provider注册进eureka服务列表内
- service-url:
- register-with-eureka: true
- fetch-registry: true
- defaultZone: http://eureka7001.com:7001/eureka
输入两个参数:Header Name、Value,向下游请求地址添加 Header 信息,示例配置:
- spring:
- cloud:
- gateway:
- routes:
- - id: add_request_header_route
- uri: https://anoyi.com
- filters:
- - AddRequestHeader=X-Request-Foo, Bar
AddRequestHeader 结合 Path 路由,再添加 Header 信息,示例配置
- spring:
- cloud:
- gateway:
- routes:
- - id: add_request_header_route
- uri: https://anoyi.com
- predicates:
- - Path=/foo/{segment}
- filters:
- - AddRequestHeader=X-Request-Foo, Bar-{segment}
输入两个参数:Header Name、Value,下游请求完成后在 Response 添加 Header 信息,示例配置:
- spring:
- cloud:
- gateway:
- routes:
- - id: add_response_header_route
- uri: https://anoyi.com
- filters:
- - AddResponseHeader=X-Response-Foo, Bar
输入两个参数:Header Name、Strategy【可选】,Header Name 可以多个,用空格隔开,示例配置:
- spring:
- cloud:
- gateway:
- routes:
- - id: dedupe_response_header_route
- uri: https://anoyi.com
- filters:
- - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
如上所示,当下游和 Spring Cloud Gateway 都设置跨域时,将在 Response Header 中移除重复的 Access-Control-Allow-Credentials 和 Access-Control-Allow-Origin。
strategy 可设置的值以及配置方式如下:
- spring:
- cloud:
- gateway:
- routes:
- - id: dedupe_response_header_route
- uri: https://anoyi.com
- filters:
- - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin, RETAIN_LAST
具体可以参考:Spring Cloud Gateway - 过滤法则 - 简书 (jianshu.com)
自定义全局GlobalFilter

- @Component //必须加,必须加,必须加
- public class MyLogGateWayFilter implements GlobalFilter,Ordered
- {
- @Override
- public Mono
filter(ServerWebExchange exchange, GatewayFilterChain chain) - {
- System.out.println("time:"+new Date()+"\t 执行了自定义的全局过滤器: "+"MyLogGateWayFilter"+"hello");
-
- String uname = exchange.getRequest().getQueryParams().getFirst("uname");
- if (uname == null) {
- System.out.println("****用户名为null,无法登录");
- exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
- return exchange.getResponse().setComplete();
- }
- return chain.filter(exchange);
- }
-
- @Override
- public int getOrder()
- {
- return 0;
- }
- }