【GateWay】微服务网关Gateway、动态路由、断言Predicate、自定义GlobalFilter

1、GateWay是什么

Cloud全家桶中有个很重要的组件就是网关,在1.x版本中都是采用的Zuul网关
可是在2.x版本中,zuul的升级一直跳票,SpringCloud最后本身研发了一个网关代替Zuul
那就是Springcloud Gateway一句话: gateway是原zuul 1.x版的替代java

1.1 一句话形容Gateway

Springcloud Gateway使用的Webflux中的reactor-netty响应式编程组件,底层使用了Netty通信框架react

1.2 微服务架构中网关在那里

在这里插入图片描述

2、有Zuul了怎么又出来了gateway

2.1 咱们为何选择Gateway

neflix不太靠谱,zuul2.0一直跳票,迟迟不发布web

2.2 SpringCloud Gateway具备以下特性
  1. 基于Spring Framework 5,Project Reactor 和 Spring Boot 2.0 进行构建
  2. 动态路由:可以匹配任何请求属性
  3. 能够对路由指定 Predicate (断言)和 Filter(过滤器)
  4. 集成Hystrix的断路器功能
  5. 集成Spring Cloud 服务发现功能
  6. 易于编写的 Predicate(断言)和Filter(过滤器)
  7. 请求限流功能
  8. 支持路径重写
2.3 SpringCloud Gateway 与 Zuul的区别

SpringCloud Finchley正式版以前,Spring Cloud 推荐的网关是Netflix提供的Zuul正则表达式

  1. Zull 1.x 是一个基于阻塞 I/O 的API Gateway
  2. Zull 1.x 基于Sevlet 2.5 使用阻塞构架它不支持任何长链接(如 WebSocket) Zuul的设计模式和Nginx较像,每次I/O操做都是从工做线程中选择一个执行,请求线程被阻塞到工做线程完成,可是差异是Nginx用C++实现,Zuul用Java实现,而JVM自己会有第一次加载较慢的状况,使得Zuul的性能相对较差
  3. Zuul 2.x 理念更先进,想基于Netty非阻塞和支持长链接,但SpringCloud目前尚未整合。Zuul 2.x的性能较1.x又较大i生。在性能方面,根据官网提供的基准测试,Spring Cloud Gateway 的 RPS(每秒请求数)是zuul的1.6倍
  4. Spring Cloud Gateway创建在Spring Framework 5, Project Reactor 和 Spring Boot 2之上,使用非阻塞的API
  5. Spring Cloud Gateway还支持 WebSocket,而且与Spring紧密集成拥有更好的开发体验。

3、Zuul 1.x 模型

在这里插入图片描述
在这里插入图片描述
加粗样式
Zuul 1.x 是基于servlet之上的一个阻塞式处理模型,即spring实现了处理全部request请求的一个servlet 并由该servlet阻塞式处理处理,因此Springcloud Zuul没法摆脱serverlet模型的弊端spring

4、Gateway模型

在这里插入图片描述

5、Gateway三大核心概念

5.1 Route 路由

路由是构建网关的基本模块,它由ID,目标URI,一系列的断言和过滤器组成,若是断言为true则匹配该路由apache

5.2 Predicate(断言)

参考的是Java8的java.util.function.Predicate
开发人员能够匹配HTTP请求中的全部内容(例如请求头或请求参数),若是请求与断言相匹配则进行路由编程

5.3 Filter(过滤)

指的是Spring框架中GatewayFilter的实例,使用过滤器,能够在请求被路由器前或者以后对请求进行修改。设计模式

5.4 整体

在这里插入图片描述
Web请求,经过一系列匹配条件,定位到真正的服务节点。并在这个转发过程的先后,进行一些精细化的控制
predicate就是咱们的匹配条件
filter,能够理解为一个无所不能的拦截器。有了这两个元素在加上目标uri,就能够实现一个具体的路由了api

6、Gateway的工做流程

6.1 官网总结

在这里插入图片描述

  • 客户端向Spring Cloud Gateway发出请求。而后在Gateway Handler Mapping 中找到与请求相匹配的路由,将其发送到Gateway Web Handler
  • Handler 再经过指定的过滤器链来将请求发送到咱们实际的服务执行业务逻辑,而后返回
  • 过滤器之间用虚线分开是由于过滤器可能会再发送代理请求以前(“pre”)或以后(“post")执行业务逻辑
  • Filter在”pre"类型的过滤器能够作参数校验,权限校验,流量监控,日志输出,协议转换等,在"post"类型的过滤器中能够作响应式内容,响应头的修改,日志的输出,流量监控等有着很是重要的做用。
6.2 核心逻辑

路由转发+执行过滤器链架构

7、 新建module cloud-gateway-gateway9527

7.1 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.aiguigu.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-gateway-gateway9527</artifactId>

    <dependencies>
        <!--gateway-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <!--eureka client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!--引入自定义的api通用包,可以使用Payment支付Entity-->
        <dependency>
            <groupId>com.aiguigu.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>compile</scope>
        </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>
7.2 application.yml
server:
  port: 9527

spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      routes:
        - id: payment_routh #payment_routh    #路由的ID,没有固定规则但要求惟一,简易配合服务名
          uri: http://localhost:8001         #匹配后提供服务的路由地址
          predicates:
            - Path=/payment/get/** #断言,路径相匹配的进行路由 - id: payment_routh2 #payment_routh #路由的ID,没有固定规则但要求惟一,简易配合服务名 uri: http://localhost:8001 #匹配后提供服务的路由地址 predicates: - Path=/payment/lb/** #断言,路径相匹配的进行路由 eureka: instance: hostname: cloud-gateway-service client: fetch-registry: true register-with-eureka: true service-url: #设置与Eureka Server交互的地址查询服务和注册服务都须要依赖这个地址 # defaultZone: http://eureka7002.com:7002/eureka/ # 单机版eureka defaultZone: http://eureka7001.com:7001/eureka/ 
7.3 主启动类
package com.atguigu.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);
    }
}
7.4 测试

已经注册成功:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

7.4 路由器的另一种配置方法

这里新建一个config
在这里插入图片描述
配置路由规则,代替yml配置

package com.atguigu.springcloud.config;

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class GatewayConfig {
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder){
        RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();

        routes.route("path_route_atguigu",
                r -> r.path("/guonei").uri("http://news.baidu.com/guonei")).build();
        return routes.build();
    }
}

测试:
在这里插入图片描述

8、动态路由

8.1 修改yml

在这里插入图片描述
在这里插入图片描述

8.2 测试

在这里插入图片描述

9、Gateway经常使用的Preducate(断言)

9.1 断言的种类

请求要知足断言表达式为true才能访问,只要一个不符合就访问不到服务
在这里插入图片描述

9.2 配置时间断言

在当前时间以后才能访问
在这里插入图片描述
时间格式复杂怎么办?这里有生成当前时间的方法

import java.time.ZonedDateTime;

public class TimeBulider {
    public static void main(String[] args) {
        ZonedDateTime zonedDateTime=ZonedDateTime.now();
        System.out.println(zonedDateTime);
    }
}

测试,若是我将时间调至明天,再次访问会出现找不到服务
在这里插入图片描述
能够看到这里断言还有After,Before和Between,方法都是大同小异
在这里插入图片描述

9.3 Cookie断言
  • Cookie Route Predicate须要两个参数,一个是Cookie name ,一个是正则表达式
  • 路由规则会经过获取对应的Cookie name 值和正则表达式去匹配,若是匹配上就去执行路由,若是没有匹配上则不执行

在这里插入图片描述

  • 以上是配置的Cookie
  • 下面咱们用命令框的CURL去访问,出现了负载均衡
    在这里插入图片描述
9.4 Header断言
- Header=X-Request-Id, \d+ 
 #请求头须要有X-Request-Id属性名,值为整数正则表达式

命令输入:http://localhost:9527/payment/lb -H “X-Request-Id:1234”,负数就直接报错在这里插入图片描述

9.5 总结

全部断言不一一举例了,说白了Predicate就是为了实现一组匹配规则,让请求过来找到对应的Route进行处理
在这里插入图片描述

10、Gateway的filter

  • 指的是Spring框架中GatewayFilter的实例,使用过滤器,能够请求被路由前或者以后对请求进行修改
  • 路由过滤器可用于进入的HTTP 请求和返回的HTTP响应,路由过滤器只能指定路由进行使用
  • Spring cloud Gateway内置了多种路由器,他们都由GatewayFile的工厂类来产生
  • 经常使用的GatewayFilter有31种
  • 全局的Filter有10种
10.1 自定义全局GlobalFilter

建立Gateway配置类
在这里插入图片描述
实现一个GlobalFilter

package com.atguigu.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.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

@Component
@Slf4j
@Order(0)
public class MyLogGateWayFilter implements GlobalFilter,Ordered{
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("***************Come in My LogGlobalFilter "+new Date());
        String uname = exchange.getRequest().getQueryParams().getFirst("uname");
        if(uname==null){
            log.info("*******用户名非法,请稍后再试!");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();

        }
        return chain.filter(exchange);
    }

// @Override 实现上面@Order(0)注解就能够不用实现接口
   public int getOrder() {
        return 0;
    }
}

测试
注意:请求进来必须带有uname的参数才能够访问,测试以下
在这里插入图片描述