springboot使用阿里限流框架-sentinel

当前项目源码

控制台下载

启动bin中的看板服务:账号密码:sentinel/sentinel

官方文档地址

项目引入依赖

xml 复制代码
<!-- sentinel注解支持 -->
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-annotation-aspectj</artifactId>
    <version>1.8.8</version>
</dependency>
<!-- 参数限流 -->
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-parameter-flow-control</artifactId>
    <version>1.8.8</version>
</dependency>
<!-- 限流客户端插件,默认读取资源配置sentinel.properties -->
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-transport-simple-http</artifactId>
    <version>1.8.8</version>
</dependency>

SpringBoot中自动配置

  • 创建配置类
java 复制代码
/**
 * 容器启动成功后配置Sentinel规则
 */
@Data
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "sentinel")
public class SentinelConfig implements InitializingBean {
    private List<FlowRule> rules;
    private List<ParamFlowRule> params;

    /**
     * 开启注解
     */
    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }

    /**
     * 加载规则
     */
    public void loadRules() {
        log.info("加载限流规则");
        FlowRuleManager.loadRules(rules);
        ParamFlowRuleManager.loadRules(params);
    }

    @Override
    public void afterPropertiesSet() {
        triggerSentinelInit();
        loadRules();
    }

    /**
     * 触发sentinel初始化。
     */
    private static void triggerSentinelInit() {
        new Thread(InitExecutor::doInit).start();
    }

}
  • application.yml配置文件添加内容
yml 复制代码
sentinel:
  # 资源限流
  rules:
    - resource: "test"
      count: 1
      grade: 1
  # 参数限流
  params:
    - resource: "test"
      param-idx: 0
      count: 1
      grade: 1
  • 资源目录中添加sentinel配置sentinel.properties
  • sentinel-transport-simple-http插件自动读取这个文件
properties 复制代码
project.name=sentinel-test
# 配置sentinel控制台地址
csp.sentinel.dashboard.server=localhost:8181

创建测试接口

java 复制代码
@Slf4j
@RestController
@ControllerAdvice // 使用当前类配置异常拦截
@RequestMapping("test")
public class TestController {

    @GetMapping
    @SentinelResource(
            value = "test",  // 资源名称
            blockHandler = "testBlock",// 规则异常
            blockHandlerClass = TestFallbackHandler.class,
            fallback = "testFallback", // 业务异常降级
            fallbackClass = TestFallbackHandler.class,
            exceptionsToIgnore = {CustomException.class} // 忽略异常,比如自定义异常可能在@ControllerAdvice配置
    )
    public String test(String value) {
        if ("admin".equalsIgnoreCase(value)) {
            throw new CustomException("管理员不能操作");
        }
        // 模拟未知异常
        if (Math.random() > 0.8) {
            throw new RuntimeException("其他异常情况");
        }
        log.info("request test path :{}", value);
        return "访问成功";
    }

    /**
     * 拦截CustomException异常
     */
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public String handleCustomException(CustomException ex) {
        return "自定义异常:" + ex.getMessage();
    }

    /**
     * 自定义异常
     */
    public static class CustomException extends RuntimeException {
        public CustomException(String message) {
            super(message);
        }
    }


    /**
     * 熔断降级单独类处理
     */
    public static class TestFallbackHandler {
        /**
         * 规则熔断处理
         *
         * @param value 这里参数需要跟原参数对应,否则不能触发熔断方法
         * @param ex    必须有异常参数
         */
        public static String testBlock(String value, BlockException ex) {
            return "当前访问过于频繁,请稍后再试";
        }

        /**
         * 业务降级处理
         *
         * @param value 这里参数需要跟原参数对应,否则不能触发熔断方法
         * @param ex    必须有异常参数
         */
        public static String testFallback(String value, Throwable ex) {
            log.warn("触发熔断降级,value={}, 异常类型: {}", value, ex.getClass().getName());
            return "降级处理:" + ex.getClass().getName();
        }
    }
}

测试

访问http://localhost:8080/test 应该返回"访问成功"


访问http://localhost:8080/test?value=admin 应该返回"自定义异常:管理员不能操作" 的异常信息


频繁访问http://localhost:8080/test 应该返回"当前访问过于频繁,请稍后再试"


访问http://localhost:8080/test?value=test 随机数大于0.8 "降级处理:java.lang.RuntimeException"

控制台

  • 启动.bat脚本
shell 复制代码
title sentinel-dashboard
java -Dserver.port=8181 ^
-Dcsp.sentinel.dashboard.server=localhost:8181 ^
-Dproject.name=sentinel-dashboard ^
-jar sentinel-dashboard-1.8.8.jar
相关推荐
我命由我1234510 小时前
Python Flask 开发:在 Flask 中返回字符串时,浏览器将其作为 HTML 解析
服务器·开发语言·后端·python·flask·html·学习方法
IT_陈寒10 小时前
JavaScript 性能优化:5个被低估的V8引擎技巧让你的代码提速50%
前端·人工智能·后端
想用offer打牌10 小时前
数据库大事务有什么危害(面试版)
数据库·后端·架构
Jaising66610 小时前
Spring 错误使用事务导致数据可见性问题分析
数据库·spring boot
踏浪无痕10 小时前
别再只会用 Feign!手写一个 Mini RPC 框架搞懂 Spring Cloud 底层原理
后端·面试·架构
NMBG2210 小时前
外卖综合项目
java·前端·spring boot
小徐Chao努力10 小时前
Spring AI Alibaba A2A 使用指南
java·人工智能·spring boot·spring·spring cloud·agent·a2a
用户6956194403711 小时前
前后端分离VUE3+Springboot项目集成PageOffice核心代码
后端
rannn_11111 小时前
【Git教程】概述、常用命令、Git-IDEA集成
java·git·后端·intellij-idea
我家领养了个白胖胖11 小时前
向量化和向量数据库redisstack使用
java·后端·ai编程