Sentinel入门与进阶:微服务流量控制的最佳实践 ( 六 )

8.Gateway 整合 Sentinel(熔断、限流)

8.1.引入依赖

在 Spring Cloud Alibaba 2.1.6之前的版本,引入的是 sentinel-spring-cloud-gateway-adapter 包,并且需要自己实现好多配置类,2.1.6 之后的版本内部已经帮我们实现好了,所以使用起来比较简单了。

xml 复制代码
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!--2.1.6之前的版本是 adapter 的包,整合比较麻烦,需要写配置类-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>

8.2.配置 application.yml

需要 配置的是 gateway 和 sentinel

yaml 复制代码
        
 server:
  port: 19999       
 spring:
  application:
    name: sentinel-gateway
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
        namespace: 10001
        group: DEFAULT_GROUP 
    gateway:   #配置gateway
      discovery:
        locator:
          lowerCaseServiceId: true
          enabled: true  #默认为false,true:开启通过微服务名访问
      routes:
        - id: nacos-route
          uri: lb://nacos-demo
          predicates:
            - Path=/nacosdemo/**
          filters:
            - StripPrefix=1

    sentinel:
      transport:
        dashboard: localhost:8080
      eager: true
      filter:
        enabled: false

8.3.sentinel 启动

sentinel 启动成功后界面发生变化

8.4.sentinel 配置限流规则

8.4.1.规则配置

以下配置说明:

API 名称:这个相当于一个服务的一个API的唯一ID;

阈值类型:1个 QPS 是完整的一次请求,发出请求并且拿到完成的请求结果;

QPS 阈值:每秒最大的QPS数;

间隔:请求间隔最大时间;

Burst size:宽容次数,比如我配置的是每秒访问3次以上进行流控,如果这个参数设置为 1 ,则每秒访问 4 次以上进行流控。

8.4.2.测试结果

测试,则返回 429 (429 是 Too Many Request 错误码)。

8.5.sentinel 配置熔断规则

8.5.1.规则配置

以 异常数 降级来举例

熔断策略:以什么样的策略熔断;

慢调用比例:请求超过最大RT值,比如 1ms;

熔断时长:接口发生异常后熔断时长;

最小请求次数:每秒请求最少的失败次数;

统计时长:在一定的时间段内最少请求 2 次,每个请求超过1ms, 请求数量大于 50%;

8.5.2.测试结果

测试,则会熔断,返回 DegradeException 异常,降级异常。

8.6.自定义流控降级异常信息

8.6.1.通过配置类配置

在 SentinelConfig 类中加入 init() 初始化方法(要用 @PostConstruct 注解进行初始化),定义异常处理提示信息即可。

java 复制代码
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class SentinelConfig {
    @PostConstruct
    public void init(){
        BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                Map<String, String> result = new HashMap<>();
                result.put("code", HttpStatus.TOO_MANY_REQUESTS.toString());
                result.put("msg", "服务压力过大,请稍后重试!");
                return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS).contentType(MediaType.APPLICATION_JSON).body(BodyInserters.fromValue(result));
            }
        };
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }

}

8.6.2.通过application.yml 配置

主要配置 spring.cloud.sentinel.scg.fallback 即可。

yaml 复制代码
 server:
  port: 19999       
 spring:
  application:
    name: sentinel-gateway
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
        namespace: 10001
        group: DEFAULT_GROUP 
    gateway:   #配置gateway
      discovery:
        locator:
          lowerCaseServiceId: true
          enabled: true  #默认为false,true:开启通过微服务名访问
      routes:
        - id: nacos-route
          uri: lb://nacos-demo
          predicates:
            - Path=/nacosdemo/**
          filters:
            - StripPrefix=1

    sentinel:
      transport:
        dashboard: localhost:8080
      eager: true
      filter:
        enabled: false
        
      scg:
        fallback:
          mode: response
          response-body: '{"code":"429 TOO_MANY_REQUEST", "msg":"服务压力过大,请稍后重试!"}'

8.6.3.测试结果

配置服务流控或者降级,阈值设置为1(总之小一点),快速发送请求返回自定义服务流控降级信息。

相关推荐
呱牛do it18 分钟前
企业级门户网站设计与实现:基于SpringBoot + Vue3的全栈解决方案(Day 5)
java·vue
练习时长一年19 分钟前
Spring配置类的演化
java·spring boot·spring
喜欢流萤吖~35 分钟前
服务间的依赖管理:微服务的协作之道
java·微服务
invicinble40 分钟前
Spring如何把bean注册到容器里
java·后端·spring
代码不加糖1 小时前
0基础搭建前后端分离项目:实现菜单与界面左右布局
java·前端·javascript·mysql·elementui·mybatis
希望永不加班1 小时前
SpringBoot 敏感数据脱敏(序列化层)
java·spring boot·后端·spring
希望永不加班1 小时前
SpringBoot 数据库索引优化:慢查询分析
java·数据库·spring boot·后端·spring
胡利光1 小时前
Harness Engineering 02|Repo Harness:让仓库对 Agent 可读
java·junit·单元测试
langsiming2 小时前
【无标题】
java·开发语言·数据库
weisian1512 小时前
Java并发编程--45-分布式一致性协议入门:Raft、Paxos与ZAB的核心思想
java·分布式·raft·paxos·zab