目录
- 一、概述简介
 - 1.官网
 - 2.是什么
 - 3.能干嘛
 - 4.微服务架构中网关在哪里
 
- 二、三大核心概念
 - 1.Route(路由)
 - 2.Predicate(断言)
 - 3.Filter(过滤)
 - 4.总体
 
- 三、Gateway工作流程
 - 1.官网总结
 - 2.核心逻辑:路由转发+执行过滤器链
 
- 四、入门配置
 - 1.新建Module
 - 2.POM
 - 3.YML
 - 4.业务类
 - 5.主启动类
 - 6.9527网关如何做路由映射呢???
 - 7.YML新增网关配置
 - 8.测试
 - 5.通过微服务名实现动态路由
 - 5.1.启动
 - 5.2.POM
 - 5.3.YML
 - 5.4.测试
 
- 6.Predicate的使用
 - 6.1.是什么
 - 6.2.Route Predicate Factories这个是什么东东?
 - 6.3.常用的Route Predicate
 
- 7.Filter的使用
 - 7.1.是什么
 - 7.2.Spring Cloud Gateway的Filter
 - 7.3.常用的GatewayFilter
 - 7.4.自定义过滤器
 
代码链接
 https://github.com/lidonglin-bit/cloud
一、概述简介
1.官网
https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/
 
2.是什么
Cloud全家桶中有个很重要的组件就是网关,在1.x版本中都是采用的Zuul网关
https://github.com/Netflix/zuul/wiki
 但在2.x版本中,zuul的升级一直跳票,SpringCloud最后自己研发了一个网关代替Zull,那就是SpringCloud Geteway;
 Geteway是原Zuul1.x版的替代
 
 概述
 Gateway是在spring生态系统之上构建的API网关服务,基于Spring5,SpringBoot2和Project Reactor等技术。
 Gateway旨在提供一种简单而有效的方式来对API进行路由,以及提供一些强大的过滤器功能,例如:熔断、限流、重试等
 
 SpringCloud Gateway是SpringCloud的一个全新项目,基于Spring5.0+SpringBoot2.0和Project Reactor等技术开发的网关,它旨在为微服务架构提供一种简单有效的统一的API路由管理方式。
 为了提升网关的性能,SpringCloud Gatway是基于WebFlux框架实现的,而WebFlux框架底层则使用了高性能的Reactor模式通讯框架Netty。
 SpringCloud Gateway的目标提供统一的路由方式且基于Filter链的方式提供了网关基本的功能,例如:安全、监控/指标、和限流。
 一句话
 Spring Cloud Gateway 使用的Webflux中的reactor-netty响应式编程组件,底层使用了Netty通讯框架
 
3.能干嘛
- 反向代理
 - 鉴权
 - 流量控制
 - 熔断
 - 日志监控
 
4.微服务架构中网关在哪里

二、三大核心概念
1.Route(路由)
路由是构建网关的基本模块,它由ID,目标URI,一系列的断言和过滤器组成,如果断言为true则匹配该路由
2.Predicate(断言)
参考的是java8的java.util.function.Predicate开发人员可以匹配HTTP请求中的所有内容(例如请求头或请求参数),如果请求与断言相匹配则进行路由
3.Filter(过滤)
指的是Spring框架中GatewayFilter的实例,使用过滤器,可以在请求被路由前或者之后对请求进行修改。
4.总体

 Web请求,通过一些匹配条件,定位到真正的服务节点。并在这个转发过程的前后,进行一些精细化控制。
 Predicate就是我们的匹配条件: 而Filter,就是可以理解为一个无所不能的拦截器。有了这两个元素,再加上目标uri,就可以实现一个具体的路由了。
三、Gateway工作流程
1.官网总结
https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#gateway-how-it-works
 
 
 客户端向Spring Cloud Gateway发出请求。然后在Gateway Handler Mapping中找到与请求匹配的路由,将其发送到Gateway Web Handler.
 Handler再通过指定的过滤器链来将请求发送给我们实际的服务执行业务逻辑,然后返回。
 过滤器之间用虚线分开是因为过滤器可能会在发送代理请求之前(“pre”)或之后(“post”)执行业务逻辑。
Filter在"pre"类型的过滤器可以做参数校验、权限校验、流量监控、日志输出、协议转换等,在"post"类型的过滤器中可以做响应内容、响应头的修改,日志的输出,流量控制等有着非常重要的作用
2.核心逻辑:路由转发+执行过滤器链
四、入门配置
1.新建Module
cloud-gateway-gateway9527
2.POM
<?xml version="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>cloud2020</artifactId>
        <groupId>com.donglin.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>cloud-gateway-gateway9527</artifactId>
    <dependencies>
        <!--新增gateway,不需要引入web和actuator模块-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>com.donglin.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>
 
3.YML
server:
  port: 9527
spring:
  application:
    name: cloud-gateway
eureka:
  instance:
    hostname: cloud-gateway-service
  client:
      register-with-eureka: true
      fetch-registry: true
      service-url:
          defaultZone: http://localhost:7001/eureka
 
4.业务类
无
5.主启动类
package com.donglin.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class GateWayMain9527 {
    public static void main(String[] args) {
            SpringApplication.run( GateWayMain9527.class,args);
        }
}
 
6.9527网关如何做路由映射呢???
我们目前不想暴露8001端口,希望在8001外面套一层9527
7.YML新增网关配置
server:
  port: 9527
spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      routes:
       - id: payment_routh #路由的ID,没有固定规则但要求唯一,建议配合服务名
         uri: http://localhost:8001   #匹配后提供服务的路由地址
         predicates:
           - Path=/payment/get/**   #断言,路径相匹配的进行路由
 
       - id: payment_routh2
         uri: http://localhost:8001
         predicates:
           - Path=/payment/lb/**   #断言,路径相匹配的进行路由
eureka:
  instance:
    hostname: cloud-gateway-service
  client:
    service-url:
      register-with-eureka: true
      fetch-registry: true
      defaultZone: http://localhost:7001/eureka
 
8.测试
启动7001:cloud-eureka-server7001
 启动8001:cloud-provider-payment8001
 启动9527网关:cloud-gateway-gateway9527
 访问说明
 
 添加网关前: http://localhost:8001/payment/get/31
 添加网关后: http://localhost:9527/payment/get/31
5.通过微服务名实现动态路由
默认情况下Gateway会根据注册中心的服务列表,以注册中心上微服务名为路径创建动态路由进行转发,从而实现动态路由的功能
5.1.启动
一个eureka7001+两个服务提供者8001/8002
5.2.POM
5.3.YML
server:
  port: 9527
spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true  #开启从注册中心动态创建路由的功能,利用微服务名进行路由
      routes:
        - id: payment_routh #路由的ID,没有固定规则但要求唯一,建议配合服务名
          #uri: http://localhost:8001   #匹配后提供服务的路由地址
          uri: lb://cloud-payment-service
          predicates:
            - Path=/payment/get/**   #断言,路径相匹配的进行路由
 
        - id: payment_routh2
          #uri: http://localhost:8001   #匹配后提供服务的路由地址
          uri: lb://cloud-payment-service
          predicates:
            - Path=/payment/lb/**   #断言,路径相匹配的进行路由
eureka:
  instance:
    hostname: cloud-gateway-service
  client:
    service-url:
      register-with-eureka: true
      fetch-registry: true
      defaultZone: http://localhost:7001/eureka
 
需要注意的是uri的协议为lb,表示启用Gateway的负载均衡功能。
 lb://serviceName是spring cloud gateway在微服务中自动为我们创建的负载均衡uri
5.4.测试
http://localhost:9527/payment/lb
 8001/8002两个端口切换
6.Predicate的使用
6.1.是什么
启动我们的gatewat9527,查看启动日志
 
6.2.Route Predicate Factories这个是什么东东?

Spring Cloud Gateway将路由匹配作为Spring WebFlux HandlerMapper基础框架的一部分。
 Spring Cloud Gateway包括许多内置的Route Predicate工厂。所有这些Predicate都与HTTP请求的不同属性匹配。多个Route Predicate工厂可以进行组合
 Spring Cloud Gateway创建Route对象时,使用RoutePredicateFactory创建Predicate对象,Predicate对象可以赋值给 Route。Spring Cloud Gateway包含许
 多内置的Route Predicate Factories。
 所有这些谓词都匹配HTTP请求的不同属性。多种谓词工厂可以组合,并通过逻辑and 。
6.3.常用的Route Predicate
1.After Route Predicate
 
ZonedDateTime zonedDateTime = ZonedDateTime.now();
 System.out.println(zonedDateTime);
- After=2020-03-08T10:59:34.102+08:00[Asia/Shanghai] 
  
- 测试:没到时间进行测试报错
 
 

 2.Before Route Predicate
- YML 
  
- Before=2020-03-08T10:59:34.102+08:00[Asia/Shanghai]
 
 
3.Between Route Predicate
- YML 
  
- Between=2020-03-08T10:59:34.102+08:00[Asia/Shanghai] , 2020-03-08T10:59:34.102+08:00[Asia/Shanghai]
 
 
4.Cookie Route Predicate
 
- YML 
  
- Cookie=username,atguigu #并且Cookie是username=zhangshuai才能访问
 
 - 不带cookies访问
 

- 带上cookies访问 
  
- curl下载地址:https://curl.haxx.se/download.html
 
 

- 加入curl返回中文乱码(帖子): https://blog.csdn.net/leedee/article/details/82685636
 
5.Header Route Predicate
 
- YML 
  
- Header=X-Request-Id, \d+ #请求头中要有X-Request-Id属性并且值为整数的正则表达式
 
 

 6.Host Route Predicate
 YML: - Host=**.donglin.com
7.Method Route Predicate
 YML:- Method=GET
 8.Path Route Predicate
 YML:
 9. Query Route Predicate
 YML: - Query=username, \d+ #要有参数名称并且是正整数才能路由
 10.小总结
- All
 
server:
  port: 9527
spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true  #开启从注册中心动态创建路由的功能,利用微服务名进行路由
      routes:
        - id: payment_routh #路由的ID,没有固定规则但要求唯一,建议配合服务名
          #uri: http://localhost:8001   #匹配后提供服务的路由地址
          uri: lb://cloud-payment-service
          predicates:
            - Path=/payment/get/**   #断言,路径相匹配的进行路由
        - id: payment_routh2
          #uri: http://localhost:8001   #匹配后提供服务的路由地址
          uri: lb://cloud-payment-service
          predicates:
            - Path=/payment/lb/**   #断言,路径相匹配的进行路由
            #- After=2020-03-08T10:59:34.102+08:00[Asia/Shanghai]
            #- Cookie=username,zhangshuai #并且Cookie是username=zhangshuai才能访问
            #- Header=X-Request-Id, \d+ #请求头中要有X-Request-Id属性并且值为整数的正则表达式
            #- Host=**.atguigu.com
            #- Method=GET
            #- Query=username, \d+ #要有参数名称并且是正整数才能路由
eureka:
  instance:
    hostname: cloud-gateway-service
  client:
    service-url:
      register-with-eureka: true
      fetch-registry: true
      defaultZone: http://localhost:7001/eureka
 
说白了,Predicate就是为了实现一组匹配规则,让请求过来找到对应的Route进行处理
7.Filter的使用
7.1.是什么
路由过滤器可用于修改进入的HTTP请求和返回的HTTP响应,路由过滤器只能指定路由进行使用。
 SpringCloud Gateway内置了多种路由过滤器,他们都由GatewayFilter的工厂类来产生。
 
7.2.Spring Cloud Gateway的Filter
1.生命周期,Only Two
- pre 
  
- 在业务逻辑之前
 
 - post 
  
- 在业务逻辑之后
 
 
2.种类,Only Two
 https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.2.RELEASE/reference/html/#gatewayfilter-factories
 1)GatewayFilter(31种之多)
 
 2)GlobalFilter
 
7.3.常用的GatewayFilter
AddRequestParameter
 YML
 
 省略
 …
7.4.自定义过滤器
1.自定义全局GlobalFilter
 两个主要接口介绍
 impiemerts GlobalFilter ,Ordered
 2.能干嘛
 全局日志记录
 统一网关鉴权
 。。。。。。
 3.案例代码
package com.donglin.springcloud.filter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Date;
@Component
@Slf4j
public class MyLogGateWayFilter implements GlobalFilter,Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("*********come in MyLogGateWayFilter: "+new Date());
        String uname = exchange.getRequest().getQueryParams().getFirst("username");
        if(StringUtils.isEmpty(username)){
            log.info("*****用户名为Null 非法用户,(┬_┬)");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }
    @Override
    public int getOrder() {
        return 0;
    }
}
 
4.测试
 启动
 
正确:http://localhost:9527/payment/lb?username=z3
 错误:http://localhost:9527/payment/lb?uname=z3






![[Vulnhub] DC-7](https://img-blog.csdnimg.cn/3dc31de370ea4adb9e8a829b55dedb12.png)












