官方文档链接https://sentinelguard.io/zh-cn/docs/annotation-support.html
示例
@GetMapping("/testA")
@SentinelResource(value = "testA",blockHandler = "deal")
public String testA(){
return "testA";
}
//这里是异常类型BlockException
public String deal(BlockException exception){
return "这是一个兜底方法";
}
将兜底方法和业务方法分离
@GetMapping("/testB")
@SentinelResource(value = "testB",blockHandlerClass = CustomerBlockHandler.class,blockHandler =
"handlerException")
public String testB(){
return "testB";
}
public class CustomerBlockHandler{
//这里要static静态方法
public static String handlerException(BlockException exception){
return "按客戶自定义,global handlerException----1";
}
public static String handlerException2(BlockException exception){
return "按客戶自定义,global handlerException----2";
}
}
示例
@GetMapping("/testC")
@SentinelResource(value = "testC",fallback = "fallbackMethod")
public String testC(){
throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
}
//注意这里类型是Throwable
public String fallbackMethod(Throwable exception){
return "这是一个程序异常后的默认方法,异常信息:" + exception.getMessage();
}
fallback方法和业务方法分离
@GetMapping("/testC")
@SentinelResource(value = "testC",fallbackClass = fallBackHandler.class,fallback = "fallbackMethod")
public String testC(){
throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
}
public class fallBackHandler {
//静态方法
public static String fallbackMethod(Throwable exception) {
return "这是一个程序异常后的全局方法,异常信息:" + exception.getMessage();
}
}
特别地,若 blockHandler 和 fallback 都进行了配置,则被限流降级而抛出 BlockException
时只会进入 blockHandler
处理逻辑。若未配置 blockHandler
、fallback
和 defaultFallback
,则被限流降级时会将 BlockException
直接抛出。
这里需要注意下兜底方法和原方法参数关系哈....