SpringCloud05-GateWay、Config、Bus、Stream、Sleuth

SpringCloud05

GateWay

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

一、是什么

在这里插入图片描述

在这里插入图片描述

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

SpringCloud Gateway作为Spring Cloud 生态系统中的网关,目标是替代Zuul,在Spring Cloud 2.0以上版本中,没有对新版本的Zuul 2.0以上最新高性能版本进行集成,仍然还是使用的Zuul 1.x非Reactor模式的老版本。而为了提升网关的性能,SpringCloud Gateway是基于WebFlux框架实现的,而WebFlux框架底层则使用了高性能的Reactor模式通信框架Netty。

Spring Cloud Gateway的目标提供统一的路由方式且基于 Filter链的方式提供了网关基本的功能,例如:安全,监控/指标,和限流。

一句话:SpringCloud GateWay使用的WebFlux中的reactor-netty响应式编程组件,底层使用了Netty通讯框架

在这里插入图片描述

二、非阻塞异步模型

SpringCloud Gateway具有如下特性

1.基于Spring Framework 5,Project Reactor和Spring Boot 2.0进行构建;

2.动态路由:能够匹配任何请求属性;

3.可以对路由指定Predicate (断言)和Filter(过滤器);

4.集成Hystrix的断路器功能;

5.集成Spring Cloud 服务发现功能;

6.易于编写的Predicate (断言)和Filter (过滤器);

7.请求限流功能;

8.支持路径重写。

WebFlux

官网:https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#spring-webflux

传统的Web框架,比如说: Struts2,SpringMVC等都是基于Servlet APl与Servlet容器基础之上运行的。

但是在Servlet3.1之后有了异步非阻塞的支持。而WebFlux是一个典型非阻塞异步的框架,它的核心是基于Reactor的相关API实现的。相对于传统的web框架来说,它可以运行在诸如Netty,Undertow及支持Servlet3.1的容器上。非阻塞式+函数式编程(Spring 5必须让你使用Java 8)。

Spring WebFlux是Spring 5.0 引入的新的响应式框架,区别于Spring MVC,它不需要依赖Servlet APl,它是完全异步非阻塞的,并且基于Reactor来实现响应式流规范。

三、工作流程

三大核心概念

1.Route(路由) - 路由是构建网关的基本模块,它由ID,目标URI,一系列的断言和过滤器组成,如断言为true则匹配该路由;

2.Predicate(断言) - 参考的是Java8的java.util.function.Predicate,开发人员可以匹配HTTP请求中的所有内容(例如请求头或请求参数),如果请求与断言相匹配则进行路由;

3.Filter(过滤) - 指的是Spring框架中GatewayFilter的实例,使用过滤器,可以在请求被路由前或者之后对请求进行修改。拦截器

在这里插入图片描述

web 请求,通过一些匹配条件,定位到真正的服务节点。并在这个转发过程的前后,进行一些精细化控制。

predicate 就是我们的匹配条件,而filter,就可以理解为一个无所不能的拦截器。有了这两个元素再加上目标uri,就可以实现一个具体的路由。

在这里插入图片描述

Clients make requests to Spring Cloud Gateway. If the Gateway Handler Mapping determines that a request matches a route, it is sent to the Gateway Web Handler. This handler runs the request through a filter chain that is specific to the request. The reason the filters are divided by the dotted line is that filters can run logic both before and after the proxy request is sent. All “pre” filter logic is executed. Then the proxy request is made. After the proxy request is made, the “post” filter logic is run.

客户端向Spring Cloud Gateway发出请求。然后在Gateway Handler Mapping 中找到与请求相匹配的路由,将其发送到GatewayWeb Handler。

Handler再通过指定的过滤器链来将请求发送到我们实际的服务执行业务逻辑,然后返回。

过滤器之间用虚线分开是因为过滤器可能会在发送代理请求之前(“pre”)或之后(“post")执行业务逻辑。

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

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

四、Gateway9527搭建

1.建module

新建:cloud-gateway-gateway9527

2.pom

<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>
        <dependency>
            <groupId>org.shy</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>1.0-SNAPSHOT</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>

3.yml

server:
  port: 9527

spring:
  application:
    name: cloud-gateway

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

4.启动类

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

我们目前不想暴露8001端口,希望在8001外面套一层9527

5.yml新增网关配置

server:
  port: 9527

spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      routes:
        - id: payment_routh #payment_route    #路由的ID,没有固定规则但要求唯一,建议配合服务名
          uri: http://localhost:8001          #匹配后提供服务的路由地址
          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
  client: #服务提供者provider注册进eureka服务列表内
    service-url:
      register-with-eureka: true
      fetch-registry: true
      defaultZone: http://eureka7001.com:7001/eureka

6.测试

启动7001

启动8001-cloud-provider-payment8001

启动9527网关

访问:

  • http://eureka7001.com:7001/
  • 查看两个服务是否注册成功
  • http://localhost:8001/payment/get/1
  • http://localhost:9527/payment/get/1

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

第一种:yml配置

第二种:代码中注入RouteLocator的Bean

官网:https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#modifying-the-way-remote-addresses-are-resolved

在这里插入图片描述

百度国内新闻网址,需要外网 - http://news.baidu.com/guonei

业务需求 - 通过9527网关访问到外网的百度新闻网址

编写config.GateWayConfig

在这里插入图片描述

照着官网的写

package com.shy.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 routes(RouteLocatorBuilder builder) {
   
        RouteLocatorBuilder.Builder routes = builder.routes();
        routes.route("path_route_shy",r -> r.path("/lady").uri("http://news.baidu.com/lady")).build();
        return routes.build();
    }
}

测试

访问:http://localhost:9527/lady

六、配置动态路由

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

启动

  • eureka7001
  • payment8001/8002

yml

server:
  port: 9527

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

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

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

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

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

测试

开启以下服务:

在这里插入图片描述

访问:http://localhost:9527/payment/lb

刷页面,看效果

七、常用的Predicate

在这里插入图片描述

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

Route Predicate Factories

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

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

常用的Route Predicate Factory

1.The After Route Predicate Factory

2.The Before Route Predicate Factory

3.The Between Route Predicate Factory

4.The Cookie Route Predicate Factory

5.The Header Route Predicate Factory

6.The Host Route Predicate Factory

7.The Method Route Predicate Factory

8.The Path Route Predicate Factory

9.The Query Route Predicate Factory

10.The RemoteAddr Route Predicate Factory

11.The weight Route Predicate Factory

After

1.改9527的yml

在这里插入图片描述

2.写个测试类

获取上面格式的时间戳字符串

	@Test
    public void test(){
   
        ZonedDateTime zbj = ZonedDateTime.now();
        System.out.println(zbj);
    }
	//2021-05-17T22:57:17.624+08:00[Asia/Shanghai]
3.测试

改时间测试之前之后

在这里插入图片描述

访问:http://localhost:9527/payment/lb

After,Before,Between自己测一下

Cookie

在这里插入图片描述

键值对:- Cookie=username,sshy,注意空格

测试:

在这里插入图片描述

该命令相当于发get请求,且没带cookie

带Cookie:curl http://localhost:9527/payment/lb --cookie “username=sshy”

这里注意引号中写自己的键值对

在这里插入图片描述

Header

和Cookie差不多

predicates:
	- Path=/payment/lb/**         # 断言,路径相匹配的进行路由
	- Header=X-Request-Id, \d+ # 请求头要有 X-Request-Id 属性,并且值为整数的正则表达式~

测试:cmd:curl http://localhost:9527/payment/lb -H “X-Request-Id:123”

带指定请求头的参数的CURL命令

想细看还是看官网~

八、Filter

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

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

Spring Cloud Gateway的Filter:

生命周期:

pre

post

种类(具体看官方文档

  • GatewayFilter -单一 有31种

  • GlobalFilter - 全局 有10种

常用的GatewayFilter:AddRequestParameter GatewayFilter

自定义全局GlobalFilter

两个主要接口介绍:

  1. GlobalFilter
  2. Ordered

改个代码看看效果~

GateWay9527项目添加MyLogGateWayFilter类,继承这两个接口

package com.shy.springcloud.filter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值