[Alibaba微服务技术入门]_Sentinel自定义限流处理逻辑_第16讲

以前当 Sentinel 对接口进行限流时,我们可以通过 @SentinelResource 注解中的 blockHander 属性定义限流后处理结果。但是有一点不足:处理逻辑会和业务接口的代码偶会,所以为了解决这个问题,我们可以通过Sentinel自定义限流处理逻辑来最终解决此问题。

第一步:创建CustomerHandler类,用于Sentinel自定义处理逻辑

复制代码
package com.liuyangjava.handler;

import com.alibaba.csp.sentinel.slots.block.BlockException;

public class CustomerHandler {

    public static String handlerException(BlockException e) {
        return "自定义限流处理逻辑,此时请求数过多";
    }

}
复制代码

第二步:创建RateController类

复制代码
package com.liuyangjava.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.liuyangjava.handler.CustomerHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RateController {
    @GetMapping("/sentinel/customHandler")
    @SentinelResource(value = "customHandler", blockHandlerClass = CustomerHandler.class, blockHandler = "handlerException")
    public String customHandler() {
        return "sentinel service is success";
    }
}
复制代码

第三步:添加限流规则

 

注意:

  • @SentinelResource注解不支持private方法 
  • fallback属性,主要管Java的异常
  • blockHandler属性,主要管配置规则,如:限流规则,降级规则,热点参数限流等等

 

posted @   子墨老师  阅读(97)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示