Spring Cloud(6)服务网关——Gateway

一、简介

在SpringCloud微服务体系中,有个很重要的组件就是网关,在1.x版本中都是采用的Zuul网关;但在2.x版本中,zuul的升级一直跳票,SpringCloud最后自己研发了一个网关替代Zuul,那就是SpringCloud Gateway。

Spring Cloud Gateway旨在提供一种简单而有效的方法对API进行路由,并为它们提供关于安全性、监控指标和弹性等方面的横切关注点(AOP思想)。

在这里插入图片描述
上图中是核心的流程图,最主要的就是Route、Predicates 和 Filters 作用于特定路由。

  • 路由(route):路由是构建网关的基本模块,它由ID,目标URI,一系列的断言和过滤器组成,如果总断言为true则匹配该路由
  • 断言(predicates):参照Java8的新特性Predicate。这允许开发人员匹配HTTP请求中的任何内容,比如头或参数。
  • 过滤器(filters):可以在发送下游请求之前或之后修改请求和响应。

在这里插入图片描述

  1. 客户端向 Spring Cloud Gateway 发出请求。
  2. 在 Gateway Handler Mapping 中找到与请求相匹配的路由,将其发送到 Gateway Web Handler。
  3. Gateway Web Handler 再通过指定的过滤器链来将请求发送到我们实际的服务执行业务逻辑,然后返回。
  4. 过滤器之间用虚线分开是因为过滤器可能会在发送代理请求之前(“pre”)或之后(“post”)执行业务逻辑。

其核心逻辑就是:路由转发+执行过滤器链

二、代码测试

pom.xml文件:

<?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>cloud</artifactId>
        <groupId>com.example</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-gateway</artifactId>

    <dependencies>
        <dependency>
            <groupId>com.example</groupId>
            <artifactId>common</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

</project>

(一)路由网关配置

1. YML文件配置

application.yml

server:
  port: 9999

spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      routes:
        - id: payment_route1
          uri: http://localhost:8001
          predicates:
            - Path=/payment/get/**
        - id: payment_route2
          uri: http://localhost:8001
          predicates:
            - Path=/payment/lb/**

eureka:
  client:
    #表示是否将自己注册进EurekaServer默认为true。
    register-with-eureka: true
    #是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
    fetchRegistry: true
    service-url:
      #单机版
      #defaultZone: http://localhost:7001/eureka
      # 集群版
      defaultZone: http://localhost:7001/eureka,http://localhost:7002/eureka

启动端口号为8001的payment服务;启动gateway服务。
在这里插入图片描述
在这里插入图片描述

2. 配置类

新增如下配置类:

@Configuration
public class GatewayConfig {

    @Bean
    public RouteLocator myRouteLocator(RouteLocatorBuilder routeLocatorBuilder) {
        RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();
        routes.route("test_path1", r -> r.path("/news").uri("https://news.baidu.com")).build();
        routes.route("test_path2", r -> r.path("/163").uri("https://www.163.com")).build();
        return routes.build();
    }
}

分别访问:http://localhost:9999/news http://locahost:9999/163 跳转至百度新闻和163首页。

3. 动态路由

修改yml文件:

server:
  port: 9999

spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      routes:
        - id: payment_route1
          uri: lb://CLOUD-PAYMENT
          predicates:
            - Path=/payment/get/**
        - id: payment_route2
          uri: lb://CLOUD-PAYMENT
          predicates:
            - Path=/payment/lb/**
      discovery:
        locator:
          enabled: true  #开启从注册中心动态创建路由功能,使用微服务名
eureka:
  client:
    #表示是否将自己注册进EurekaServer默认为true。
    register-with-eureka: true
    #是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
    fetchRegistry: true
    service-url:
      #单机版
      #defaultZone: http://localhost:7001/eureka
      # 集群版
      defaultZone: http://localhost:7001/eureka,http://localhost:7002/eureka
  • uri的协议为lb,表示启用Gateway的负载均衡功能。
  • lb://serviceName是spring cloud gateway在微服务中自动为我们创建的负载均衡uri

启动8001和8002的服务,在eureka注册中心注册的服务名为CLOUD-PAYMENT。

再次访问:http://localhost:9999/payment/lb 和 http://localhost:9999/payment/get/1
由8001和8002轮流提供服务。

(二)断言(predicates)

  1. The After Route Predicate Factory
spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - After=2021-04-13T12:00:00.000+08:00[Asia/Shanghai]

校验请求中的datetime,表示在北京时间(东八区Asia/Shanghai)2021年4月13日12点之后生效。
此外还有以下官方的predicates(官方文档):

  • The Before Route Predicate Factory 时间节点前生效
  • The Between Route Predicate Factory 两个时间点之间生效
  • The Cookie Route Predicate Factory 判断Cookie
  • The Header Route Predicate Factory 判断头部信息(通过name和regexp参数对)
  • The Host Route Predicate Factory 判断Host
  • The Method Route Predicate Factory 判断方法(POST、GET)
  • The Path Route Predicate Factory 判断路径
  • The Query Route Predicate Factory query值
  • The RemoteAddr Route Predicate Factory 远程地址
  • The Weight Route Predicate Factory 路由权重

(三) 过滤器(filters)

1. 概述

过滤器可用于修改进入的HTTP请求和返回的HTTP响应,滤器只能指定路由进行使用。
Spring Cloud Gateway内置了多种路由过滤器,其中GatewayFilter的工厂 类定义了31种过滤器和7种全局过滤器(官方文档

2. 自定义全局过滤器
@Component
@Slf4j
public class CustomGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("==========进入了UsernameFilter过滤器" + new Date());
        String username = exchange.getRequest().getQueryParams().getFirst("username");
        log.info("=====username: " + username);
        if (username == null || username.equals("")) {
            log.info("===========用户名为空,非法访问");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

此时,直接访问http://localhost:9999/payment/lb
返回406错误(HttpStatus.NOT_ACCEPTABLE)
打印日志:在这里插入图片描述

访问:http://localhost:9999/payment/lb?username=111
可正常返回

附:项目源码github

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值