GateWay简介

Spring Cloud GateWay是Spring Cloud的⼀个全新项⽬,⽬标是取代Netflflix Zuul,它基于Spring5.0 + SpringBoot2.0 + WebFlux(基于⾼性能的Reactor模式响应式通信框架Netty,异步⾮阻塞模型)等技术开发,性能⾼于Zuul,官⽅测试,GateWay是Zuul的1.6倍,旨在为微服务架构提供⼀种简单有效的统⼀的API路由管理⽅式。Spring Cloud GateWay不仅提供统⼀的路由⽅式(反向代理)并且基于 Filter(定义过滤器对请求过滤,完成⼀些功能) 链的⽅式提供了⽹关基本的功能,例如:鉴权、流量控制、熔断、路径重写、⽇志监控等。
⽹关在架构中的位置
image.png

GateWay核⼼概念

Zuul1.x 阻塞式IO 2.x 基于Netty
Spring Cloud GateWay天⽣就是异步⾮阻塞的,基于Reactor模型⼀个请求—>⽹关根据⼀定的条件匹配—匹配成功之后可以将请求转发到指定的服务地址;⽽在这个过程中,我们可以进⾏⼀些⽐较具体的控制(限流、⽇志、⿊⽩名单)

  • 路由(route): ⽹关最基础的部分,也是⽹关⽐较基础的⼯作单元。路由由⼀个ID、⼀个⽬标URL(最终路由到的地址)、⼀系列的断⾔(匹配条件判断)和Filter过滤器(精细化控制)组成。如果断⾔为true,则匹配该路由。
  • 断⾔(predicates):参考了Java8中的断⾔java.util.function.Predicate,开发⼈员可以匹配Http请求中的所有内容(包括请求头、请求参数等)(类似于nginx中的location匹配⼀样),如果断⾔与请求相匹配则路由。
  • 过滤器(fifilter):⼀个标准的Spring webFilter,使⽤过滤器,可以在请求之前或者之后执⾏业务逻辑。

image.png
其中,Predicates断⾔就是我们的匹配条件,⽽Filter就可以理解为⼀个⽆所不能的拦截器,有了这两个元素,结合⽬标URL,就可以实现⼀个具体的路由转发。

GateWay⼯作过程

image.png
来⾃官⽅的描述图
客户端向Spring Cloud GateWay发出请求,然后在GateWay Handler Mapping中找到与请求相匹配的路由,将其发送到GateWay Web Handler;Handler再通过指定的过滤器链来将请求发送到我们实际的服务执⾏业务逻辑,然后返回。过滤器之间⽤虚线分开是因为过滤器可能会在发送代理请求之前(pre)或者之后(post)执⾏业务逻辑。

Filter在“pre”类型过滤器中可以做参数校验、权限校验、流量监控、⽇志输出、协议转换等,在“post”类型的过滤器中可以做响应内容、响应头的修改、⽇志的输出、流量监控等。

GateWay核⼼逻辑:路由转发+执⾏过滤器链

GateWay应⽤

使⽤⽹关对⾃动投递微服务进⾏代理(添加在它的上游,相当于隐藏了具体微服务的信息,对外暴露的是⽹关)

  • 创建⼯程lg-cloud-gateway-server-9002导⼊依赖

GateWay不需要使⽤web模块,它引⼊的是WebFlux(类似于SpringMVC)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <groupId>org.example</groupId>
  6. <modelVersion>4.0.0</modelVersion>
  7. <artifactId>lg-cloud-gateway-server</artifactId>
  8. <!--spring boot ⽗启动器依赖-->
  9. <parent>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-parent</artifactId>
  12. <version>2.1.6.RELEASE</version>
  13. </parent>
  14. <dependencies>
  15. <dependency>
  16. <groupId>org.springframework.cloud</groupId>
  17. <artifactId>spring-cloud-commons</artifactId>
  18. </dependency>
  19. <dependency>
  20. <groupId>org.springframework.cloud</groupId>
  21. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  22. </dependency>
  23. <!--GateWay ⽹关-->
  24. <dependency>
  25. <groupId>org.springframework.cloud</groupId>
  26. <artifactId>spring-cloud-starter-gateway</artifactId>
  27. </dependency>
  28. <!--引⼊webflux-->
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter-webflux</artifactId>
  32. </dependency>
  33. <!--⽇志依赖-->
  34. <dependency>
  35. <groupId>org.springframework.boot</groupId>
  36. <artifactId>spring-boot-starter-logging</artifactId>
  37. </dependency>
  38. <!--测试依赖-->
  39. <dependency>
  40. <groupId>org.springframework.boot</groupId>
  41. <artifactId>spring-boot-starter-test</artifactId>
  42. <scope>test</scope>
  43. </dependency>
  44. <!--lombok⼯具-->
  45. <dependency>
  46. <groupId>org.projectlombok</groupId>
  47. <artifactId>lombok</artifactId>
  48. <version>1.18.4</version>
  49. <scope>provided</scope>
  50. </dependency>
  51. <!--引⼊Jaxb,开始-->
  52. <dependency>
  53. <groupId>com.sun.xml.bind</groupId>
  54. <artifactId>jaxb-core</artifactId>
  55. <version>2.2.11</version>
  56. </dependency>
  57. <dependency>
  58. <groupId>javax.xml.bind</groupId>
  59. <artifactId>jaxb-api</artifactId>
  60. </dependency>
  61. <dependency>
  62. <groupId>com.sun.xml.bind</groupId>
  63. <artifactId>jaxb-impl</artifactId>
  64. <version>2.2.11</version>
  65. </dependency>
  66. <dependency>
  67. <groupId>org.glassfish.jaxb</groupId>
  68. <artifactId>jaxb-runtime</artifactId>
  69. <version>2.2.10-b140310.1920</version>
  70. </dependency>
  71. </dependencies>
  72. <dependencyManagement>
  73. <!--spring cloud依赖版本管理-->
  74. <dependencies>
  75. <dependency>
  76. <groupId>org.springframework.cloud</groupId>
  77. <artifactId>spring-cloud-dependencies</artifactId>
  78. <version>Greenwich.RELEASE</version>
  79. <type>pom</type>
  80. <scope>import</scope>
  81. </dependency>
  82. </dependencies>
  83. </dependencyManagement>
  84. <build>
  85. <plugins>
  86. <!--编译插件-->
  87. <plugin>
  88. <groupId>org.apache.maven.plugins</groupId>
  89. <artifactId>maven-compiler-plugin</artifactId>
  90. <configuration>
  91. <source>11</source>
  92. <target>11</target>
  93. <encoding>utf-8</encoding>
  94. </configuration>
  95. </plugin>
  96. <!--打包插件-->
  97. <plugin>
  98. <groupId>org.springframework.boot</groupId>
  99. <artifactId>spring-boot-maven-plugin</artifactId>
  100. </plugin>
  101. </plugins>
  102. </build>
  103. </project>

注意:不要引⼊starter-web模块,需要引⼊web-flflux

  • application.yml 配置⽂件部分内容 ```xml server: port: 9002 spring: application: name: lg-cloud-gateway cloud: gateway:
    1. routes: # 路由可以有多个
    2. - id: service-autodeliver-router # 我们⾃定义的路由 ID,保持唯⼀
    3. uri: http://127.0.0.1:8091 # ⽬标服务地址 ⾃动投递微服务(部署多实例) 动态路由:uri配置的应该是⼀个服务名称,⽽不应该是⼀个具体的服务实例的地址
    4. # gateway⽹关从服务注册中⼼获取实例信息然后负载后路由
    5. predicates: #断⾔:路由条件,Predicate 接受⼀个输⼊参数,返回⼀个布尔值结果。该接⼝包含多种默 认⽅法来将 Predicate 组合成其他复杂的逻辑(⽐如:与,或,⾮)。
    6. - Path=/autodeliver/**
    7. - id: service-resume-router # 我们⾃定义的路由 ID,保持唯⼀
    8. uri: http://127.0.0.1:8081 # ⽬标服务地址#http://localhost:9002/resume/openstate/1545132 #http://127.0.0.1:8081/openstate/1545132
    9. predicates: #断⾔:路由条件,Predicate 接受⼀个输⼊参数,返回⼀个布尔值结果。该接⼝包含多种默 认⽅法来将 Predicate 组合成其他复杂的逻辑(⽐如:与,或,⾮)。
    10. - Path=/resume/**
    11. filters:
    12. - StripPrefix=1
    eureka: client: service-url:
    1. defaultZone: http://lgcloudeurekaservera:8761/eureka/,http://lgcloudeurekaserverb:8762/eureka/ #把 eureka 集群中的所有 url 都填写了进来,也可以只写⼀台,因为各个 eureka server 可以同步注册表
    instance:

    使⽤ip注册,否则会使⽤主机名注册了(此处考虑到对⽼版本的兼容,新版本经过实验都是ip)

    prefer-ip-address: true

    ⾃定义实例显示格式,加上版本号,便于多版本管理,注意是ip-address,早期版本是ipAddress

    instance-id: ${spring.cloud.client.ip-address}:${spring.application.name}:${server.port}:@project.version@
  1. 上⾯这段配置的意思是,配置了⼀个 id service-autodeliver-router 的路由规则,当向⽹关发起请求 http://localhost:9002/autodeliver/checkAndBegin/1545132,请求会被分发路由到对应的微服务上
  2. <a name="7p6Si"></a>
  3. # GateWay路由规则详解
  4. Spring Cloud GateWay 帮我们内置了很多 Predicates功能,实现了各种路由匹配规则(通过 Header、请求参数等作为条件)匹配到对应的路由。
  5. ![image.png](https://cdn.nlark.com/yuque/0/2021/png/12497888/1618036490496-88f9d2c7-d3fa-4edf-b784-be9338879c2b.png#crop=0&crop=0&crop=1&crop=1&height=418&id=NMg8B&margin=%5Bobject%20Object%5D&name=image.png&originHeight=835&originWidth=1788&originalType=binary&ratio=1&rotation=0&showTitle=false&size=155317&status=done&style=none&title=&width=894)<br />时间点后匹配
  6. ```java
  7. spring:
  8. cloud:
  9. gateway:
  10. routes:
  11. - id: after_route
  12. uri: https://example.org
  13. predicates:
  14. - After=2017-01-20T17:42:47.789-07:00[America/Denver]

时间点前匹配

  1. spring:
  2. cloud:
  3. gateway:
  4. routes:
  5. - id: before_route
  6. uri: https://example.org
  7. predicates:
  8. - Before=2017-01-20T17:42:47.789-07:00[America/Denver]

指定Header正则匹配指定值

  1. spring:
  2. cloud:
  3. gateway:
  4. routes:
  5. - id: header_route
  6. uri: https://example.org
  7. predicates:
  8. - Header=X-Request-Id, \d+

请求Host匹配指定值

  1. spring:
  2. cloud:
  3. gateway:
  4. routes:
  5. - id: host_route
  6. uri: https://example.org
  7. predicates:
  8. - Host=**.somehost.org,**.anotherhost.org
  1. spring:
  2. cloud:
  3. gateway:
  4. routes:
  5. - id: path_route
  6. uri: https://example.org
  7. predicates:
  8. - Path=/red/{segment},/blue/{segment}

GateWay动态路由详解

GateWay⽀持⾃动从注册中⼼中获取服务列表并访问,即所谓的动态路由
实现步骤如下
1)pom.xml中添加注册中⼼客户端依赖(因为要获取注册中⼼服务列表,eureka客户端已经引⼊)
2)动态路由配置

image.png
注意:动态路由设置时,uri以 lb: //开头(lb代表从注册中⼼获取服务),后⾯是需要转发到的服务名称

GateWay过滤器

GateWay过滤器简介

从过滤器⽣命周期(影响时机点)的⻆度来说,主要有两个pre和post:

image.png
从过滤器类型的⻆度,Spring Cloud GateWay的过滤器分为GateWayFilter和GlobalFilter两种

image.png
如Gateway Filter可以去掉url中的占位后转发路由,⽐如

  1. predicates:
  2. - Path=/resume/**
  3. filters:
  4. - StripPrefix=1 # 可以去掉resume之后转发

注意:GlobalFilter全局过滤器是使⽤⽐较多的过滤器,我们主要讲解这种类型

⾃定义全局过滤器实现IP访问限制(⿊⽩名单)

请求过来时,判断发送请求的客户端的ip,如果在⿊名单中,拒绝访问⾃定义GateWay全局过滤器时,我们实现Global Filter接⼝即可,通过全局过滤器可以实现⿊⽩名单、限流等功能。

  1. package org.example.cloud.filter;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.cloud.gateway.filter.GatewayFilterChain;
  4. import org.springframework.cloud.gateway.filter.GlobalFilter;
  5. import org.springframework.core.Ordered;
  6. import org.springframework.core.io.buffer.DataBuffer;
  7. import org.springframework.http.HttpStatus;
  8. import org.springframework.http.server.reactive.ServerHttpRequest;
  9. import org.springframework.http.server.reactive.ServerHttpResponse;
  10. import org.springframework.stereotype.Component;
  11. import org.springframework.web.server.ServerWebExchange;
  12. import reactor.core.publisher.Mono;
  13. import java.util.ArrayList;
  14. import java.util.List;
  15. import java.util.Objects;
  16. /**
  17. * @author: xjlonly
  18. * @date: Created in 2021/4/10 15:04
  19. * @description:定义全局过滤器 会对所以路由生效
  20. * @modified By:
  21. * @version: 1.0
  22. */
  23. @Slf4j
  24. @Component
  25. public class BlackListFilter implements GlobalFilter, Ordered {
  26. // 模拟⿊名单(实际可以去数据库或者redis中查询)
  27. private static final List<String> blackList = new ArrayList<>();
  28. static {
  29. blackList.add("0:0:0:0:0:0:0:1"); // 模拟本机地址
  30. }
  31. /**
  32. * 过滤器核⼼⽅法
  33. * @param exchange 封装了request和response对象的上下⽂
  34. * @param chain ⽹关过滤器链(包含全局过滤器和单路由过滤器)
  35. * @return
  36. */
  37. @Override
  38. public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
  39. // 思路:获取客户端ip,判断是否在⿊名单中,在的话就拒绝访问,不在的话就放⾏
  40. // 从上下⽂中取出request和response对象
  41. ServerHttpRequest request = exchange.getRequest();
  42. ServerHttpResponse response = exchange.getResponse();
  43. // 从request对象中获取客户端ip
  44. String clientIp = Objects.requireNonNull(request.getRemoteAddress()).getHostString();
  45. if(blackList.contains(clientIp)){
  46. // 决绝访问,返回
  47. response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态
  48. log.debug("=====>IP:" + clientIp + " 在⿊名单中,将被拒绝访问!");
  49. String data = "Request be denied!";
  50. DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
  51. response.writeWith(Mono.just(wrap));
  52. }
  53. // 合法请求,放⾏,执⾏后续的过滤器
  54. return chain.filter(exchange);
  55. }
  56. /**
  57. * 返回值表示当前过滤器的顺序(优先级),数值越⼩,优先级越⾼
  58. * @return
  59. */
  60. @Override
  61. public int getOrder() {
  62. return 0;
  63. }
  64. }

GateWay⾼可⽤

⽹关作为⾮常核⼼的⼀个部件,如果挂掉,那么所有请求都可能⽆法路由处理,因此我们需要做GateWay的⾼可⽤。
GateWay的⾼可⽤很简单:可以启动多个GateWay实例来实现⾼可⽤,在GateWay的上游使⽤Nginx等负载均衡设备进⾏负载转发以达到⾼可⽤的⽬的。
启动多个GateWay实例(假如说两个,⼀个端⼝9002,⼀个端⼝9003),剩下的就是使⽤Nginx等完成负载代理即可。示例如下:

  1. #配置多个GateWay实例
  2. upstream gateway {
  3. server 127.0.0.1:9002;
  4. server 127.0.0.1:9003;
  5. }
  6. location / {
  7. proxy_pass http://gateway;
  8. }