[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 @ 2021-11-22 14:58  子墨老师  阅读(84)  评论(0编辑  收藏  举报