六、SpringCloud之网关

6.1 问题

如果让客户端直接与各个微服务通信可能出现:

  1. 客户端需要调用不同的url地址
  2. 增加难度在一定的场景下
  3. 存在跨域请求的问题每个微服务都需要进行单独的身份认证

6.2 Gateway

Spring Cloud Gateway 是 Spring Cloud 的一个全新项目,该项目是基于Netty、Reactor以及WEbFlux构建,它旨在为微服务架构提供一种简单有效的统一的 API 路由管理方式。 Spring Cloud Gateway 作为 Spring Cloud 生态,系统中的网关,目标是替代 Netflix Zuul,其不仅提供统一的路由方式,并且基于 Filter 链的方式提供了网关

基本的功能,例如:安全、监控、埋点和限流等。

6.3 Gateway的特点

优点

性能强劲,是Zuul的1.6倍 功能强大,内置了很多实用的功能,例如转发、监控、限流等 设计优雅,容易扩展

缺点

依赖Netty与WebFlux,不是传统的Servlet编程模型,有一定的学习成本不能在Servlet容器下工作,也不能构

建成WAR包,即不能将其部署在Tomcat、Jetty等Servlet容器里,只能打成jar包执行 不支持Spring Boot 1.x, 需2.0及更高的版本

6.4 Gateway的作用

Spring Cloud Security 停止维护 spring cloud security gateway_java

Spring Cloud Security 停止维护 spring cloud security gateway_spring cloud_02

6.5 Gateway核心

Route(路由)

这是Spring Cloud Gateway的基本构建块,可简单理解成一条转发规则。包含:ID、目标URL、一组断言和一

组过滤器,可以根据规则进行匹配

Predicate(断言)

这是一个 Java 8 的 Predicate,即java.util.function.Predicate这个接口,Gateway使用Predicate实现路由的匹配

条件

Filter(过滤器)

这是 org.springframework.cloud.gateway.filter.GatewayFilter 的实例,我们可以使用它修改请求和响应

6.6 Gateway的路由匹配规则

Spring Cloud Security 停止维护 spring cloud security gateway_Cloud_03

路由匹配的常用配置如下所示:

Spring Cloud Security 停止维护 spring cloud security gateway_Cloud_04

6.7 Gateway使用

1.创建项目

Ticket_Gateway

2.依赖jar

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        <version>2021.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-loadbalancer</artifactId>
    </dependency>
</dependencies>

3.编写配置

server:
  port: 8080
spring:
  application:
    name: LxVoteGateway #项目名,服务名
  cloud:
    nacos:
      discovery: #注册中心
        server-addr: 127.0.0.1:8848
    gateway:
      routes:
      - id: vote  #唯一
        uri: lb://LxVoteApi   #lb 从注册中心获取服务。要跳转的服务名称
        predicates:
        - Path=/vote/**   #外界的访问路径
        filters:
        - StripPrefix=1   #去除路由跳转时的路径的级别

4.开关类配置

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

5.运行测试

Spring Cloud Security 停止维护 spring cloud security gateway_java_05

6.8 基于Gateway实现过滤器

Gateway提供了2类过滤器:1.全局过滤器(GlobalFilter) 2.局部过滤器(GatewayFilter)

开发中主要使用全局过滤器

实现步骤:

1.编写类 实现接口GlobalFilter

2.重写方法filter

@Component
public class HelloFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request=exchange.getRequest();
        //获取请求的ip地址
        System.err.println(request.getRemoteAddress().getHostString());

        return chain.filter(exchange);//放行
    }
}

实现版本号参数的拦截处理

@Component
public class VersionFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request=exchange.getRequest();
        ServerHttpResponse response=exchange.getResponse();
        //验证请求参数是否包含version 包含放行,不包含就拦截
        if(request.getQueryParams().containsKey("version")){
            System.err.println(request.getQueryParams().get("version"));
            //放行
            return chain.filter(exchange);
        }else {
            //拦截 同时返回消息内容
            R r= R.fail("亲,请传递version");
            response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
            //拦截并返回自定义内容
            return response.writeWith(
                    Mono.just(response.bufferFactory().
                    wrap(JSON.toJSONString(r).getBytes())));
        }
    }
}

3.运行测试

Spring Cloud Security 停止维护 spring cloud security gateway_微服务_06

七、SpringCloud之熔断器

7.1 Sentinel是什么

随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。

Spring Cloud Circuit Breaker 是 Spring Cloud 官方的熔断器组件库,提供了一套统一的熔断器抽象API接口,允

许开发者自由选择合适的熔断器实现。这个官方的熔断器组件库,截至目前,官方推荐的熔断器组件有:

Hystrix Resilience4J Sentinel Spring Retry 当前,Spring Cloud Circuit Breaker 处于孵化阶段中,未来将合并到

Spring Cloud 主干版本正式发布。

7.2 Sentinel发展历程

2012 年,Sentinel 诞生于阿里巴巴集团内部,主要功能为入口流量控制;

2013 - 2018 年,Sentinel 在阿里巴巴集团内部迅速发展,成为基础技术模块,覆盖了所有的核心场景。Sentinel 也因此积累了大量的流量控制场景以及生产实践;

2018年7月,阿里巴巴宣布限流降级框架组件 Sentinel 正式开源,在此之前,Sentinel 作为阿里巴巴“大中台、小前台”架构中的基础模块,已经覆盖了阿里的所有核心场景,因此积累了大量的流量归整场景以及生产实践;

2018年9月,Sentinel 发布 v0.2.0版本,释放异步调用支持、热点参数限流等多个重要特性;

2018年10月,Sentinel 发布首个 GA 版本 v1.3.0,该版本包括 Sentinel 控制台功能的完善和一些 bug

修复,以及其它的产品改进;

2018年12月,Sentinel发布v1.4,加入了开发者关注的集群流控功能;

2019年3月,Sentinel 发布1.5.0 ,引入 Reactive 支持;

2019年4月,Sentinel 贡献的 spring-cloud-circuitbreaker- sentinel 模块正式被Spring Cloud社区合并至 Spring Cloud Circuit Breaker,成为 Spring Cloud 官方的主流推荐选择之一。

2019年4月25日,Sentinel 发布 1.6.0 ,提供对 Spring Cloud Gateway、Zuul 等主流 API Gateway 的定制化支持。

7.3 Sentinel 的特点

丰富的应用场景:Sentinel 承接了阿里巴巴近 10 年的双十一大促流量的核心场景,例如秒杀(即突发流量控制在系统容量可以承受的范围)、消息削峰填谷、集群流量控制、实时熔断下游不可用应用等。

完备的实时监控:Sentinel 同时提供实时的监控功能。您可以在控制台中看到接入应用的单台机器秒级

数据,甚至 500 台以下规模的集群的汇总运行情况。

广泛的开源生态:Sentinel 提供开箱即用的与其它开源框架/库的整合模块,例如与 Spring Cloud、 Dubbo、gRPC 的整合。您只需要引入相应的依赖并进行简单的配置即可快速地接入 Sentinel。

完善的 SPI 扩展点:Sentinel 提供简单易用、完善的 SPI 扩展接口。您可以通过实现扩展接口来快速地

定制逻辑。例如定制规则管理、适配动态数据源等。