文章目录
前言
前面已经介绍了使用Sentinel设置限流与流控规则,这篇文章主要介绍使用@SentinelResource设置熔断;
模拟操作-blockHandler
下面的请求添加了@SentinelResource
注解,可以在Sentinel
控制台新增流控规则;
如果触发限流的话,则会执行HelloControllerBlockHandler
-indexError
方法,其中注册参数只有value
参数为必填,其他参数均可空;
如果只设置value
,限流时则触发限流异常(FlowException
);
@SentinelResource(value = "index", blockHandler = "indexError", blockHandlerClass = HelloControllerBlockHandler.class)
@ResponseBody
@GetMapping("index")
public String index() {
return "ok";
}
indexError
public String indexError(BlockException e){
if(e instanceof FlowException){
return "当前请求过于火爆,您已被流控!!";
}
if(e instanceof DegradeException){
return "当前请求过于火爆,您已被降级!!";
}
if(e instanceof ParamFlowException){
return "当前请求过于火爆,您已被热点参数限流!!";
}
return "服务器快爆了,请稍后再试!!!";
}
blockHandler
blockHandler
函数访问范围需要是public
,返回类型需要与原方法相匹配;- 参数类型需要和原方法相匹配并且最后加一个额外的参数,类型为
BlockException
;
blockHandlerClass
blockHandler
函数默认需要和原方法在同一个类中,如果希望使用其他类的函数的话,则需要指定blockHandlerClass
为对应的类的 Class 对象,注意对应的函数必需为 static 函数,否则无法解析;
模拟操作-fallback
当方法出现异常时,会执行异常降级方法:HelloControllerFallback
-indexFallback
;
和限流降级类似,只不过为一个为限流降级,一个为异常降级;
@SentinelResource(value = "index", fallback = "indexFallback", fallbackClass = HelloControllerFallback.class)
@ResponseBody
@GetMapping("index")
public String index() {
int a = 10 /0;
return "ok";
}
indexFallback
public static String indexFallback(Throwable throwable) {
throwable.printStackTrace();
log.error("异常降级:{}", throwable.getMessage());
return "fail";
}
模拟操作-defaultFallback
- 默认处理方案,可选项,通常用于通用的
fallback
逻辑; fallback
属性和defaultFallback
是指定业务代码中抛出异常的解决办法,优先执行fallback
属性;