SpringCloud08-Gateway

SpringCloud08-Gateway

1.Gateway

  1. Gateway和Zuul都是网关,但是Zuul出自Netflix,Gateway出自SpringCloud社区。
  2. Gateway基于WebFlux框架实现,WebFlux是一个典型非阻塞异步的框架,它的核心是基于Reactor的相关API实现的。相对于传统的web框架来说,它可以运行在诸如Netty,Undertow及支持Servlet3.1的容器上。同时WebFlux是Spring 5.0 引入的新的响应式框架,区别于Spring MVC,它不需要依赖Servlet APl。
  3. Zuul1.x基于Servlet 2.5使用阻塞架构,即每次I/О操作都是从工作线程中选择一个执行,请求线程被阻塞到工作线程完成,在高并发场景下没有优势。
  4. Gateway的功能:反向代理、鉴权、流量监控、熔断、日志监控......
  5. Gateway源码地址。https://github.com/spring-cloud/spring-cloud-gateway
  6. Gateway官方文档。https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/
  7. Gateway在整个应用中的位置。

image

2.Gateway三大核心概念

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

3.Gateway工作流程

  1. 客户端向Gateway发出请求,然后在Gateway Handler Mapping 中找到与请求相匹配的路由,将其发送到GatewayWeb Handler。
  2. Handler再通过指定的过滤器链来将请求发送到我们实际的服务执行业务逻辑,然后返回。Filter在“pre”中可以进行参数校验、权限校验、流量监控、日志输出、协议转换......,在“post”可以进行响应内容、响应头的修改,日志的输出,流量监控......

4.创建微服务cloud-gateway-gateway9527

  1. pom.xml
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
  1. yml
server:
  port: 9527

spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由
      routes:
        # 访问 http://127.0.0.1:9527/payment/ok/**,相当与访问 http://127.0.0.1:8001/payment/ok/**
        - id: payment_routh1 #路由的ID,没有固定规则但要求唯一,建议配合服务名使用
          uri: http://127.0.0.1:8001 #匹配后提供服务的路由地址
          predicates:
            - Path=/payment/ok/** # 断言,路径相匹配的进行路由
eureka:
  instance:
    hostname: cloud-gateway-service
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka
  1. Main
@EnableEurekaClient
@SpringBootApplication
public class CloudGatewayGateway9527Main {

    public static void main(String[] args) {
        SpringApplication.run(CloudGatewayGateway9527Main.class, args);
    }
}
  1. 没有业务类。

  2. 启动Gateway后,可以通过网关来访问服务。访问http://127.0.0.1:9527/payment/ok/,相当与访问http://127.0.0.1:8001/payment/ok/

  3. Gateway的通过代码配置网关

@Configuration
public class GatewayConfig {

    @Bean
    public RouteLocator customerRoute(RouteLocatorBuilder builder) {
        RouteLocatorBuilder.Builder routes = builder.routes();

        // 访问 http://localhost:9527/guonei 相当与访问 http://news.baidu.com/guonei
        routes.route("test01", r -> r.path("/guonei").uri("http://news.baidu.com")).build();

        return routes.build();
    }
}

5.GateWay动态路由

  1. Gateway从注册中心拉取服务的信息,以注册中心上微服务名为路径创建动态路由进行转发,从而实现动态路由的功能。
  2. yml配置。
spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由
      routes:
        - id: payment_routh2 #路由的ID,没有固定规则但要求唯一,建议配合服务名使用
          uri: lb://cloud-provider-payment
          predicates:
            - Path=/payment/get/** # 断言,路径相匹配的进行路由

6.GateWay常用的Predicate断言

  1. 时间断言,Before、After、Between。
spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
      routes
        - id: payment_routh1
          uri: lb://cloud-provider-payment
          predicates:
            - Path=/payment/ok/** # 断言,路径相匹配的进行路由
            # 这个时间后才能访问
            - After=2017-01-20T17:42:47.789-07:00[America/Denver]
            # 在这个时间之前才能访问
            - Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]
            # 在这个时间之前才能访问
            - Before=2017-01-20T17:42:47.789-07:00[America/Denver]
  1. Path,Restful格式。
spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
      routes:
        - id: payment_routh1
          uri: lb://cloud-provider-payment
          predicates:
            # /red/1 或者 /blue/1
            - Path=/red/{segment},/blue/{segment}
  1. 需要携带Cookie。
spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
      routes:
        - id: payment_routh1
          uri: lb://cloud-provider-payment
          predicates:
            - Path=/payment/ok/**
            # 需要携带Cookie 第一个参数是key,第二个参数时 value匹配的正则表达式
            - Cookie=name, t*
  1. 特定格式的请求头、host、请求方法、请求参数
spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
      routes:
        - id: payment_routh1
          uri: lb://cloud-provider-payment
          predicates:
            - Path=/payment/ok/**
            # 请求头必须是数字
            - Header=X-Request-Id, \d+
            - Host=**.cloud.org,**.anotherhost.org
            # 必须是get或者post方法
            - Method=GET,POST
            # 需要有参数key=red,value可以是 green也可以是greet
            - Query=red, gree.
            - RemoteAddr=192.168.1.1/24
  1. 权重匹配-负载均衡
# 将有80%的请求转发到8001,20%的请求进入8002
spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
      routes:
        - id: payment_routh1
          uri: http://127.0.0.1:8001
          predicates:
            - Path=/payment/user/**
            - Weight=group1, 8
        - id: payment_routh2
          uri: http://127.0.0.1:8002
          predicates:
            - Path=/payment/account/**
            - Weight=group1, 2

7.Gateway自定义Filter

@Slf4j
@Component
public class GatewayGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("=============================");
        String username = exchange.getRequest().getQueryParams().getFirst("username");
        if (StrUtil.isEmpty(username)) {
            log.info("------------- username is empty");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            // 使用直接返回
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    // 优先级
    @Override
    public int getOrder() {
        return 0;
    }
}

8.其他

  1. 获取Gateway断言需要的时区时间信息
// 获取当前时区的当前时间 2021-10-01T14:58:36.144+08:00[Asia/Shanghai]
ZonedDateTime dateTime = ZonedDateTime.now();
System.out.println(dateTime);
  1. curl测试demo
    1. 携带Cookie。Cookie=name, tcurl http://localhost:9527/payment/ok --cookie "name=tt"*。
    2. 携带Header。Header=X-Request-Id, \d+curl http://localhost:9527/payment/ok -H "X-Request-Id:1"
    3. 携带请求参数。Query=red, gree.curl http://localhost:9527/payment/ok?red=gree1,gree后面需要加一个字符。
posted @ 2021-10-07 19:58  行稳致远方  阅读(21)  评论(0)    收藏  举报