SpringCloud【进阶】07:GateWay服务网关实战教程

一、什么是gateway

gateway官网,点击查看

在这里插入图片描述
SpringCloud Gateway是Spring Cloud的一个全新项目,基于Spring 5.0+Spring Boot 2.0和Project Reactor等技术开发的网关,它旨在为微服务架构提供—种简单有效的统一的API路由管理方式。

SpringCloud Gateway是基于WebFlux框架实现的,而WebFlux框架底层则使用了高性能的Reactor模式通信框架Netty

Spring Cloud Gateway的目标提供统一的路由方式且基于 Filter链的方式提供了网关基本的功能,例如:安全,监控/指标,和限流。nginx也类似是网关的功能,通过实现动静分离,完成限流的作用
在这里插入图片描述

1、微服务架构中网关的位置

在这里插入图片描述

SpringCloud Gateway具有如下特性

  • 动态路由:能够匹配任何请求属性
  • 可以对路由指定Predicate (断言)和Filter(过滤器)
  • 集成Hystrix的断路器功能
  • 集成Spring Cloud 服务发现功能
  • 易于编写的Predicate (断言)和Filter (过滤器)
  • 请求限流功能
  • 支持路径重写

2、为什么要用网关

在这里插入图片描述

二、Gateway工作流程

1、三大核心概念
  1. Route(路由) - 路由是构建网关的基本模块,它由ID,目标URI,一系列的断言和过滤器组成,如断言为true则匹配该路由;
  2. Predicate(断言) -
    参考的是Java8的java.util.function.Predicate,开发人员可以匹配HTTP请求中的所有内容(例如请求头或请求参数),如果请求与断言相匹配则进行路由
  3. Filter(过滤) - 指的是Spring框架中GatewayFilter的实例,使用过滤器,可以在请求被路由前或者之后对请求进行修改
    在这里插入图片描述
2、Gateway工作流程

在这里插入图片描述

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

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

三、Gateway9527搭建

1、新建模块 cloud-gateway-gateway9527

2、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>springcloud</artifactId>
        <groupId>com.lian.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

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

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

    <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.lian.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>

3、YML

server:
  port: 9527

spring:
  application:
    name: cloud-gateway

#============================新增网关配置===========================================

  cloud:
    gateway:
      routes:
        - id: payment_routh #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
          uri: http://localhost:8001          #匹配后提供服务的路由地址
          #uri: lb://cloud-payment-service #匹配后提供服务的路由地址
          predicates:
            - Path=/payment/get/**         # 断言,路径相匹配的进行路由

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

#=============================新增网关配置==========================================

eureka:
  instance:
    hostname: cloud-gateway-service
  #服务提供者provider注册进eureka服务列表内
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka

4、主启动类

package com.lian.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableEurekaClient
public class GateWayMain9527 {
    public static void main(String[] args) {
        SpringApplication.run(GateWayMain9527.class,args);
    }
}

5、测试

启动7001eureka注册中心
在这里插入图片描述
启动cloud-provider-payment8001提供者

启动cloud-gateway-gateway9527网关

访问说明

添加网关前:http://localhost:8001/payment/lb
在这里插入图片描述
添加网关后:http://localhost:9527/payment/lb
在这里插入图片描述

添加网关前 - http://localhost:8001/payment/get/1
在这里插入图片描述
添加网关后 - http://localhost:9527/payment/get/1
在这里插入图片描述
两者访问成功,返回相同结果,没有暴露8001端口,成功的在外面套上了9527端口

四、Gateway配置路由的两种方式

在配置文件yml中配置,见上一章节

代码中注入RouteLocator的Bean

举个栗子:通过9527网关访问到百度新闻网址

1、cloud-gateway-gateway9527业务实现

网关类9527新建配置类,将RouteLocator注入到spring组件

package com.lian.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();
    }
}

2、测试

浏览器输入http://localhost:9527/guonei,返回http://news.baidu.com/guonei相同的页面
在这里插入图片描述
在这里插入图片描述

五、GateWay配置动态路由

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

1、yaml配置利用微服务名路由

需要注意的是uri的协议为lb,表示启用Gateway的负载均衡功能

lb://serviceName是spring cloud gateway在微服务中自动为我们创建的负载均衡uri

server:
  port: 9527

spring:
  application:
    name: cloud-gateway

#============================新增网关配置===========================================
#因为实际中同一个服务名下有很多个具体的实例服务,所以不能写死
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由
      routes:
        - id: payment_routh #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
          #uri: http://localhost:8001          #匹配后提供服务的路由地址
          uri: lb://cloud-payment-service #匹配后提供服务的路由地址
          predicates:
            - Path=/payment/get/**         # 断言,路径相匹配的进行路由

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

#=============================新增网关配置==========================================

eureka:
  instance:
    hostname: cloud-gateway-service
  #服务提供者provider注册进eureka服务列表内
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka

2、测试

启动注册中心eureka7001
启动提供者payment8001/8002
在这里插入图片描述
浏览器输入 http://localhost:9527/payment/get/1。结果不停刷新页面,8001/8002两个端口切换
在这里插入图片描述

六、GateWay常用的Predicate

1、Route Predicate Factories是什么?

Spring Cloud Gateway将路由匹配作为Spring WebFlux HandlerMapping基础架构的一部分。

Spring Cloud Gateway包括许多内置的Route Predicate工厂。所有这些Predicate都与HTTP请求的不同属性匹配。多个RoutePredicate工厂可以进行组合。

Spring Cloud Gateway创建Route 对象时,使用RoutePredicateFactory 创建 Predicate对象,Predicate 对象可以赋值给Route。Spring Cloud Gateway包含许多内置的Route Predicate Factories。
所有这些谓词都匹配HTTP请求的不同属性。多种谓词工厂可以组合,并通过逻辑and。

2、常用的Route Predicate Factory

Predicate就是为了实现一组匹配规则,让请求过来找到对应的Route进行处理

  • The After Route Predicate Factory
  • The Before Route Predicate Factory
  • The Between Route Predicate Factory
  • The Cookie Route Predicate Factory
  • The Header Route Predicate Factory
  • The Host Route Predicate Factory
  • The Method Route Predicate Factory
  • The Path Route Predicate Factory
  • The Query Route Predicate Factory
  • The RemoteAddr Route Predicate Factory
  • The weight Route Predicate Factory
server:
  port: 9527

spring:
  application:
    name: cloud-gateway

#============================新增网关配置===========================================

  cloud:
    gateway:
      routes:
        - id: payment_routh #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
          #uri: http://localhost:8001          #匹配后提供服务的路由地址
          uri: lb://cloud-payment-service #匹配后提供服务的路由地址,服务名下有多个具体实例
          predicates:
            - Path=/payment/get/**         # 断言,路径相匹配的进行路由

        - id: payment_routh2 #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
          #uri: http://localhost:8001          #匹配后提供服务的路由地址
          uri: lb://cloud-payment-service #匹配后提供服务的路由地址
          predicates:
            - Path=/payment/lb/**         # 断言,路径相匹配的进行路由
            #- After=2021-03-15T11:25:30.916+08:00[Asia/Shanghai] #在此时间之后才生效
            #- Before=2021-03-15T11:25:30.916+08:00[Asia/Shanghai] #在此时间之前才生效
            #- Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver] #在此时间之间才生效
            #- Cookie=username,zs
            #- Header=X-Request-Id, \d+
            #- Method=GET
      #开启从注册中心动态创建路由的功能,利用微服务名进行路由
      discovery:
        locator:
          enabled: true

#=============================新增网关配置==========================================

eureka:
  instance:
    hostname: cloud-gateway-service
  #服务提供者provider注册进eureka服务列表内
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka

七、GateWay的Filter

路由过滤器可用于修改进入的HTTP请求和返回的HTTP响应,路由过滤器只能指定路由进行使用。Spring Cloud Gateway内置了多种路由过滤器,他们都由GatewayFilter的工厂类来产生。

1、Spring Cloud Gateway的Filter:

生命周期:

  • pre
  • post

种类(具体看官方文档):

  • GatewayFilter - 有31种
  • GlobalFilter - 有10种

常用的GatewayFilter:AddRequestParameter GatewayFilter

2、自定义全局GlobalFilter:

两个主要接口介绍:

  • GlobalFilter
  • Ordered

能干什么:

  • 全局日志记录
  • 统一网关鉴权

举个栗子

1、GateWay9527项目添加MyLogGateWayFilter类:

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

import java.util.Date;

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

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        log.info("***********come in MyLogGateWayFilter:  "+new Date());
        String uname = exchange.getRequest().getQueryParams().getFirst("uname");
        if (uname == null){
            log.info("*******用户名为null,非法用户,o(╥﹏╥)o");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

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

2、测试

启动7001eureka注册中心
启动提供者8001和8002
启动配置filter过滤器后的网关

访问请求地址必须要加 uname,否则报错
http://localhost:9527/payment/get/1?uname=abc
在这里插入图片描述

八、总结常用网关解决方案

1、nginx+lua

在这里插入图片描述

2、kong

在这里插入图片描述

3、traefik

在这里插入图片描述

4、SpringCloudNetFlix Zuul

在这里插入图片描述

5、SpringCloud gateway

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值