Loading

SentinelResource自定义限流逻辑处理

SentinelResource除了blockHandler可以设置自定义限流处理逻辑方法以外,还提供另外一个属性来设置限流处理逻辑类型blockHandlerClass属性,此属性中设置的方法必需为 static 函数,否则无法解析。

第一步:

/**
 * 此类型用来处理限流自定义逻辑
 */
public class CustomerBlockHandler {
    public static String handlerException1(BlockException exception) {
        return "handlerException1:系统异常,请稍后重试!";
    }

    public static String handlerException2(BlockException exception) {
        return "handlerException2:网络崩溃了,请稍后重试!";
    }
}

第二步:

@RestController
public class FlowLimitController {
    /**
     * 此方法用到了自定义限流处理类型CustomerBlockHandler中的handlerException1方法来处理限流逻辑。
     */
    @GetMapping("/bycustomer")
    @SentinelResource(value = "bycustomer",
            blockHandlerClass = CustomerBlockHandler.class,
            blockHandler = "handlerException1")
    public String bycustomer(){
        return "-----bycustomer";
    }

}

第三步:

image

添加流控规则以后,我们频繁访问http://localhost:8401/bycustomer,就会看见是CustomerBlockHandler类型的handlerException1方法来处理自定义限流逻辑

image

对应关系图:

image

posted @ 2022-05-21 10:00  ZT丶  阅读(85)  评论(0编辑  收藏  举报