16_服务网关Gateway——路由以及动态路由

服务网关 Zuul Zuul2 Gateway

官网:https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/

概念:

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

Gateway是在Spring 生态系统之上构建的API网关服务,基于Spring 5,SpringBoot 2和Project Reactor等技术。Gateway旨在提供一种简单而有效的方式来对API进行路由,以及提供一些强大的过滤器功能,例如:熔断、限流、重试等。

在这里插入图片描述
功能:能干什么?

  • 反向代理
  • 鉴权
  • 流量控制
  • 熔断
  • 日志监控

微服务架构中网关的位置
在这里插入图片描述
选择GateWay的原因

  • netflix不太靠谱,zuul 2.0一直跳票,迟迟不发布
    一方面因为Zuul 1.0已经进入了维护阶段,而且Gateway是SpringCloud团队研发的,值得信赖。而且很多功能Zuul都没有用起来也非常的简单便捷。
    Gateway是基于异步非阻塞模型上进行开发的,性能方面不需要担心。虽然Netflix早就发布了最新的Zuul 2.x,但SpringCloud貌似没有整合计划。而且Netflix相关组件都宣布进入维护期。多方面综合考虑Gateway是很理想的网关选择。
  • SpringCloud Gateway具有如下特性
    基于Spring Framework 5,Project Reactor和Spring Boot 2.0构建
    动态路由:能够匹配任何请求属性
    可以对路由指定 Predicate(断言)和Filter(过滤器)
    集成Hystrix的断路器功能
    集成Spring Cloud 的服务发现功能
    易于编写的Predicate(断言)和Filter(过滤器)
    请求限流功能
    支持路径重写
  • SpringCloud Gateway 与 zuul 的区别
    在SpringCloud Finchley 正式版之前,SpringCloud推荐的网关是Netflix提供的Zuul:
    1、Zuul 1.x是一个基于阻塞 I/O 的API Gateway
    2、Zuul 1.x基于servlet 2.5使用阻塞架构它不支持任何长连接(如websocket)Zuul的设计模式和Nginx较像,每次I/O 操作都是从工作线程中选择一个执行,请求线程被阻塞到工作线程完成,但是差别是Nginx用C++实现,Zuul用Java实现,而JVM本身会有一次加载较慢的情况,使得zuul的性能相对较差
    3、Zuul 2.x理念更先进,向基于Netty非阻塞和支持长连接,但SpringCloud目前还没有整合。Zuul 2.x的性能较Zuul 1.x有较大提升。在性能方面,根据官方提供的基准测试,SpringCloud Gateway的RPS(每秒请求数)是Zuul的1.6倍
    4、SpringCloud Gateway建立在Spring Framework5、Project Reactor和Spring Boot 2之上,使用非阻塞API
    5、SpringCloud Gateway还支持WebSocket,并且与Spring紧密集成用于更好的开发体验

Gateway工作流程:

核心概念:

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

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

Gateway 工作流程

在这里插入图片描述
客户端向Spring Cloud Gateway发出请求。然后在Gateway Handler Mapping中找到与请求相匹配的路由,将其发送到Gateway Web Handler。

Handler再通过指定的过滤器链来讲请求发送到我们实际的服务执行业务逻辑,然后返回。
过滤器之间用虚线分开是因为过滤器可能会在发送代理请求之前(“pre”)或之后(“post”)执行业务逻辑

Filter 在 “pre” 类型的过滤器可以做参数校验、权限校验、流量监控、日志输出、协议转换等;在 “post” 类型的过滤器中可以做响应内容、响应头的修改,日志的输出,流量监控等,有着非常重要的作用

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

创建module cloud-gateway-gateway9527

pom文件,注意这里不需要web模块依赖,否则报错

<?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>cloud2021</artifactId>
        <groupId>com.atguigu.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.atguigu.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </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>

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:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka

以上的意思是:配置了一个 id 为 payment_routh 的路由规则,当访问地址 http://localhost:9527/payment/get/时会自动转发到地址:localhost:8001//payment/get/

主启动类:

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);
    }
}

测试:

启动7001、8001、9527,将8001、9527都注册进eureka7001

在这里插入图片描述
在这里插入图片描述
添加网关后:
在这里插入图片描述
在这里插入图片描述
9527套在最外面,有一个地址 localhost:8001 能被访问到,predicates 断言判断 8001下面有一个 /payment/get/** 地址匹配,如果路由上 predicates 为true 访问成功,false 访问失败。

Gateway网关路由有两种配置方式

  1. 在配置文件yml 中配置
  2. 代码中注入RouteLocator 的Bean

官网案例:https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#route-metadata-configuration

怎么写

添加配置类

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 {

    /**
     * 配置一个id为route-name的路由规则,
     * 当访问地址http://localhost:9527/guonei时会自动转发到地址:http://news.baidu.com/guonei
     * @param routeLocatorBuilder
     * @return
     */
    @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();
    }
}

配置了一个 id 为 path_route_atguigu 的路由规则,当访问地址 http://localhost:9527/guonei时会自动转发到地址:http://news.baidu.com/guonei

测试

在这里插入图片描述
这个就是用编码的方式实现gateway网关进行路由映射配置的方法
spring cloud gateway 网关的代码配置(网上搜的)

/**
     * spring:
     * cloud:
     * gateway:
     * routes:
     * - id: nameRoot
     * uri: http://nameservice
     * predicates:
     * - Path=/name/**
     * - Weight=service1, 95
     * filters:
     * - StripPrefix=1
     */

    private void createGatewayRoute(GatewayAppVo gatewayApp) {
        gatewayApp.getMachineList().forEach(gatewayAppMachineVo -> {
            GatewayRouteDto gatewayRouteDto = new GatewayRouteDto();
            gatewayRouteDto.setId(gatewayApp.getId() + "_" + gatewayAppMachineVo.getServerId());
            gatewayRouteDto.setPredicates(createPredicateDefinition(gatewayApp, gatewayAppMachineVo));
            gatewayRouteDto.setFilters(Collections.singletonList(createFilterDefinition()));
            gatewayRouteDto.setUri(gatewayAppMachineVo.getMachineHost());
            gatewayRouteDto.setOrder(gatewayApp.getSequence());
                redisUtils.set(STARMARK_GATEWAY_ROUTES + gatewayApp.getProjectId() + ":" + gatewayApp.getId() + "_" + gatewayAppMachineVo.getServerId(),
                        JSONObject.toJSONString(gatewayRouteDto));

        });
    }

    private List<PredicateDefinition> createPredicateDefinition(GatewayAppVo gatewayAppVo, GatewayAppMachineVo gatewayAppMachineVo) {
        List<PredicateDefinition> predicatesList = new ArrayList<>();
        //增加转发
        {
            Map<String, String> args = new HashMap<>();
            args.put("pattern", "/" + gatewayAppVo.getProjectId() + "/" + gatewayAppVo.getAccessPre());
            args.put("pathPattern", "/" + gatewayAppVo.getProjectId() + "/" + gatewayAppVo.getAccessPre());
            PredicateDefinition predicateDefinition = new PredicateDefinition();
            predicateDefinition.setArgs(args);
            predicateDefinition.setName("Path");
            predicatesList.add(predicateDefinition);
        }
        //增加权重
        if (gatewayAppMachineVo.getWeight() != null) {
            Map<String, String> args = new HashMap<>();
            args.put("weight.group", gatewayAppMachineVo.getServerId());
            args.put("weight.weight", gatewayAppMachineVo.getWeight().toString());
            PredicateDefinition predicateDefinition = new PredicateDefinition();
            predicateDefinition.setArgs(args);
            predicateDefinition.setName("Weight");
            predicatesList.add(predicateDefinition);
        }

        return predicatesList;

    }

    private FilterDefinition createFilterDefinition() {
        Map<String, String> args = new HashMap<>();
        args.put("parts", "1");
        FilterDefinition filterDefinition = new FilterDefinition();
        filterDefinition.setName("StripPrefix");
        filterDefinition.setArgs(args);
        return filterDefinition;

    }

用网关实现负载均衡:

动态路由

上面访问的路由地址我们是写死的,在微服务架构中,微服务提供者不可能只有一台服务器,就需要动态路由

在这里插入图片描述
之前80客户端发送请求访问8001/8002,通过ribbon负载均衡,将请求分散,现在服务提供者如果是多台,就需要将ribbon替换为gateway,只暴露gateway,客户端请求统一发到gateway,gateway将请求转发给8001/8002。

默认情况下Gateway会根据注册中心注册的服务列表,以注册中心上微服务名为路径创建动态路由进行转发,从而实现动态路由的功能。

现在启动一个eureka7001,两个服务提供者8001/8002

修改pom.xml,将9527注册进eureka

<dependency>
    <groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

修改yml
需要注意的是uri的协议为lb,表示启用Gateway的负载均衡功能。
lb://serviceName是springcloud gateway在微服务中自动为我们创建的负载均衡uri。

spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true   #开启从注册中心动态创建路由的功能,利用微服务名进行路由
      routes:
        - id: payment_routh #payment_routh    #路由的ID,没有固定规则但要求唯一,简易配合服务名
          #uri: http://localhost:8001         #匹配后提供服务的路由地址
          uri: lb://cloud-provider-service   #匹配后提供服务的路由地址,lb后跟提供服务的微服务的名,不要写错
          predicates:
            - Path=/payment/get/**          #断言,路径相匹配的进行路由

        - id: payment_routh2 #payment_routh   #路由的ID,没有固定规则但要求唯一,简易配合服务名
          #uri: http://localhost:8001          #匹配后提供服务的路由地址
          uri: lb://cloud-provider-service     #匹配后提供服务的路由地址,lb后跟提供服务的微服务的名,不要写错
          predicates:
            - Path=/payment/lb/**             #断言,路径相匹配的进行路由

先开启从注册中心动态创建路由的功能,利用微服务名进行路由
通过网关从注册中心中获得

启动9527,测试
在这里插入图片描述
两个微服务注册进来,微服务名一定要对应,别写错。现在再来看通过9527 访问服务,也是可以的,并且多次刷新,8001/8002交替出现。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值