Spring Cloud — Gateway

天上的星星,再多,也多不过我对你的思念,雨中的雷声很大,也大不过我对你的牵挂,得不到,是因为不属于你,放不下,因为你不甘心,失去所爱,虽然伤心,但失去不爱你的人,又有什么担心呢 ?
天空一声巨响 Spring Cloud — Gateway 闪亮登场。

Gateway简介 

Gateway的作用

Gateway工作原理

Gateway路由功能

Gateway跨域配置

Gateway过滤器

Gateway简介

1.SpringCloud GateWay是基于Spring5.0+Spring Boot2.0 和 Project Reator等技术开发的网关,目标是替代Zuul。
2.SpringCloud GateWay是基于WebFlux框架实现的,WebFlux框架底层则使用了高性能的Reactor模式通信框架Netty。

Gateway的作用

Gateway是SpringCloud提供API网关,主要起到路由和鉴权功能,以及性能监控、流量控制、统一通知等

 

Gateway工作原理

 

  1. 客户端发送请求给Gateway

  2. Gateway将请求发送给HandlerMapping处理器映射

  3. 处理器映射根据请求路由找到对应的Handler执行请求

  4. 请求执行会经过一个过滤器链,过滤器分为两种: pre 前置过滤器,主要用于鉴权;post 后置过滤器,主要用于性能监控和日志记录

  5. 如果请求正常通过过滤器链,就能访问代理的服务,最后返回数据给客户端

Gateway路由功能

使用过程:

1) 创建网关项目

2) 引入gateway依赖

3) 网关需要注册到注册中心

4) 配置路由

spring:
  cloud:
    gateway:
      routes: # 路由
      - id: order-service-route
        uri: lb://order-service
        predicates: # 断言
        - Path=/order/**,/orders/**
      - id: product-service-route
        uri: lb://product-service
        predicates: # 断言
        - Path=/product/**,/products/**

其它GateWay路由规则

时间点后匹配

spring:
  cloud:
    gateway:
      routes:
        - id: after_route
          uri: https://example.org
          predicates:
            - After=2017-01-20T17:42:47.789-07:00[America/Denver]

时间点前匹配

spring:
  cloud:
    gateway:
      routes:
      - id: before_route
        uri: https://example.org
        predicates:
        - Before=2017-01-20T17:42:47.789-07:00[America/Denver]

时间区间匹配

spring:
  cloud:
    gateway:
      routes:
      - id: between_route
        uri: https://example.org
        predicates:
        - Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]

指定Cookie正则匹配指定值

spring:
  cloud:
    gateway:
      routes:
      - id: cookie_route
        uri: https://example.org
        predicates:
        - Cookie=chocolate, ch.p

指定Header正则匹配指定值

spring:
  cloud:
    gateway:
      routes:
      - id: header_route
        uri: https://example.org
        predicates:
        - Header=X-Request-Id, \d+

请求Host匹配指定值

spring:
  cloud:
    gateway:
      routes:
      - id: host_route
        uri: https://example.org
        predicates:
        - Host=**.somehost.org,**.anotherhost.org

请求Method匹配指定请求方式

spring:
  cloud:
    gateway:
      routes:
      - id: method_route
        uri: https://example.org
        predicates:
        - Method=GET,POST

请求路径正则匹配

spring:
  cloud:
    gateway:
      routes:
      - id: path_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment},/blue/{segment}

请求包含某参数

spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: https://example.org
        predicates:
        - Query=green

请求包含某参数并且参数值匹配正则表达式

spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: https://example.org
        predicates:
        - Query=red, gree.

远程地址匹配

spring:
  cloud:
    gateway:
      routes:
      - id: remoteaddr_route
        uri: https://example.org
        predicates:
        - RemoteAddr=192.168.1.1/24

Gateway跨域配置

通过网关统一跨域,其它服务中不配置跨域

spring:
  application:
    name: gateway-service
  cloud:
    gateway:
      globalcors:
        cors-configurations: # 跨域配置
          '[/**]': # 匹配所有路径
            allowed-origins: # 允许的域名
              - "http://localhost:8080"
            allowed-headers: "*" # 允许的请求头
            allowed-methods: "*" # 允许的方法
            allow-credentials: true # 是否携带cookie

Gateway过滤器

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

生命周期时机点作用
pre这种过滤器在请求被路由之前调用。我们可利用这种过滤器实现身份验证、在集群中选择请求的微服务、记录调试信息等。
post这种过滤器在路由到微服务以后执行。这种过滤器可用来为响应添加标准的 HTTP Header、收集统计信息和指标、将响应从微服务发送给客户端等。

从过滤器类型的角度,Spring Cloud GateWay的过滤器分为GateWayFilter和GlobalFilter两种

过滤器类型影响范围
GateWayFilter应用到单个路由上
GlobalFilter应用到所有的路由上
/*
 * 模拟验证过滤器
 */
@Slf4j
public class MyAuthenticationFilter implements GlobalFilter, Ordered {
​
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获得请求和响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获得请求头中的token
        String token = request.getHeaders().getFirst("Authorization");
        //模拟解析判断
        if("123456".equals(token)){
            log.info("验证成功,放行请求:{}",request.getURI());
            return chain.filter(exchange);
        }
        // 出现错误进行拦截
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //返回验证失败的响应信息给客户端
        DataBuffer wrap = response.bufferFactory().wrap("验证错误,需要登录".getBytes());
        return response.writeWith(Mono.just(wrap));
    }
​
    @Override
    public int getOrder() {
        return 0;
    }
}
​
@Configuration
public class GlobalFilterConfig {
​
    @Bean
    public MyAuthenticationFilter authenticationFilter(){
        return new MyAuthenticationFilter();
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值