服务流控(Sentinel)

引入依赖

XML 复制代码
<!-- 必须的 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- sentinel 核心库 -->
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-core</artifactId>
    <version>1.8.0</version>
</dependency>

实现流控

编码实现

  • 限流实现
java 复制代码
    private static final Logger logger = LoggerFactory.getLogger(HelloController.class);
    private static final String RESOURCE_NAME = "hello";

    @RequestMapping("/hello")
    public String hello() {
        Entry entry = null;
        // 务必保证finally会被执行
        try {
            // 资源名可使用任意有业务语义的字符串
            entry = SphU.entry(RESOURCE_NAME);
            // 被保护的业务逻辑
            // do something...
            String str = "hello world";
            logger.info("++++++++++++" + str);
            return str;
        } catch (BlockException e1) {
            // 资源访问阻止,被限流或被降级
            // 进行相应的处理操作
            logger.info("block!!!!!");
            return "被流控了!!!!";
        } catch (Exception e) {
            // 若需要配置降级规则。则需要通过这种方式记录业务异常
            Tracer.traceEntry(e, entry);
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }
        return null;
    }
  • 注册流控规则
java 复制代码
    @PostConstruct
    private static void initFlowControlRules() { // 通常设置在服务提供方
        // 流控规则列表
        List<FlowRule> flowRuleList = new ArrayList<>();

        // 流控规则
        FlowRule helloFlowRule = new FlowRule();
        // 设置流控的资源名称
        helloFlowRule.setResource(RESOURCE_NAME);
        // 设置流控规则 QPS
        helloFlowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 设置流控的阈值
        // Set limit QPS to 20
        helloFlowRule.setCount(1);

        flowRuleList.add(helloFlowRule);
        
        FlowRuleManager.loadRules(flowRuleList);
   }
  • 效果呈现

注解实现

  • 引入依赖
XML 复制代码
<!--  @SentinelResource  -->
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-annotation-aspectj</artifactId>
    <version>1.8.0</version>
</dependency>
  • 增加切面
    • 启动类
java 复制代码
    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }
    • 配置类
java 复制代码
/**
 * 1. 使用注解@SentinelResource
 * 2. 使用了 Spring AOP
 * 3. 通过配置的方式将 SentinelResourceAspect 注册为一个 Spring Bean
 */
@Configuration
public class AopConfiguration {

    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }
}
  • 注解使用
java 复制代码
    /**
     * 使用注解 使用Sentinel
     *
     * @SentinelResource: 依赖:
     * <dependency>
     *      <groupId>com.alibaba.csp</groupId>
     *      <artifactId>sentinel-annotation-aspectj</artifactId>
     *      <version>1.8.0</version>
     * </dependency>
     * 1. value: 资源名称
     * 2. blockHandler 流控降低处理器 (默认和接口实现方法在同一个类中)
     * 3. blockHandlerClass 指定处理器类
     * 4. fallback  业务异常处理
     * 5. fallbackClass 指定异常处理器类
     * 6. blockHandler 和 fallback 同时配置, blockHandler 优先级高
     * 7. exceptionsToIgnore 排除不需要处理的异常 -> exceptionsToIgnore = {}
     */
    @RequestMapping("/user")
    @SentinelResource(value = USER_RESOURCE_NAME, blockHandler = "blockHandlerForGetUser",
//            fallback = "fallBackForGetUser",
            exceptionsToIgnore = {})
    public User getUser(String id) {
        // int i = 1 / 0;
        return new User(id, "Quentin");
    }

    /**
     * 注意:
     * 1. 必须是public, 若放在其他类中 blockHandlerClass 则必须为 public static
     * 2. 返回值 需和原接口方法的返回值保持一致 且 参数包含原方法的参数
     * 3. 额外增加  异常参数 BlockException
     *
     * @param id
     * @param be
     * @return
     */
    public User blockHandlerForGetUser(String id, BlockException be) {
        logger.info("++++++++注解流控");
        return new User(id, "被流控了!!!");
    }
  • 增加流控规则
java 复制代码
    @PostConstruct
    private static void initFlowControlRules() { // 通常设置在服务提供方
        // 流控规则列表
        List<FlowRule> flowRuleList = new ArrayList<>();


        // 流控规则
        FlowRule userFlowRule = new FlowRule();
        // 设置流控的资源名称
        userFlowRule.setResource(USER_RESOURCE_NAME);
        // 设置流控规则 QPS
        userFlowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 设置流控的阈值
        // Set limit QPS to 20
        userFlowRule.setCount(1);

        flowRuleList.add(userFlowRule);

        FlowRuleManager.loadRules(flowRuleList);
    }
  • 效果
相关推荐
葡萄成熟时 !12 小时前
JAVA 常用API学习笔记
java·笔记·学习
Rain的Java大神之路13 小时前
介绍一下分布式事务
java·分布式·后端·spring·spring cloud·架构·springcloud
吴声子夜歌14 小时前
Java面试题——基础(一)
java·开发语言
南城以南溫暖如初14714 小时前
外卖CPS实战指南:从技术选型到运营落地全流程解析
java·spring boot·mysql·架构·vue
傻啦嘿哟15 小时前
英雄联盟皮肤爬虫:爬取全皮肤价格与特效,做比价工具
java·c++·爬虫
码匠许师傅16 小时前
【C++ 面试真题】24. 聊聊 C++ 的时间日期处理
java·c++·面试
mqiqe17 小时前
AgentScope Java 2.0 Agent 状态存储(AgentStateStore)深度解析:构建可恢复、可扩展的智能体运行时
java·运维·网络
zhifou12345617 小时前
java 17升级安装
java·开发语言
用户37215742613517 小时前
如何使用 Java 将 Markdown 转换为 PDF(含自定义设置)
java
用户37215742613517 小时前
如何使用 Java 在 Word 文档中添加和删除水印:分步指南
java