在上一篇文章自定义流控规则后,如果请求失败效果如下
这种错误提示不太友好,此时可以自定义兜底逻辑
@SentinelResource注解类似于Hystrix中的@HystrixCommand注解
@SentinelResource注解中有两个属性需要我们进行区分,blockHandler属性用来指定不满足Sentinel 规则的降级兜底方法,fallback属性用于指定Java运行时异常兜底方法,如下
- 在API接口资源处配置
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.lagou.edu.config.SentinelHandlersClass;
import com.lagou.edu.controller.service.ResumeServiceFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/autodeliver")
public class AutodeliverController {
@Autowired
private ResumeServiceFeignClient resumeServiceFeignClient;
/**
* @SentinelResource value:定义资源名
* blockHandlerClass:指定Sentinel规则异常兜底逻辑所在class类
* blockHandler:指定Sentinel规则异常兜底逻辑具体哪个方法
* fallbackClass:指定Java运行时异常兜底逻辑所在class类
* fallback:指定Java运行时异常兜底逻辑具体哪个方法
*/
@GetMapping("/checkState/{userId}")
// @SentinelResource注解类似于Hystrix中的@HystrixCommand注解
@SentinelResource(value = "findResumeOpenState", blockHandlerClass = SentinelHandlersClass.class,
blockHandler = "handleException", fallbackClass = SentinelHandlersClass.class, fallback = "handleError")
public Integer findResumeOpenState(@PathVariable Long userId) {
// 模拟降级:
/*try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
// 模拟降级:异常比例
//int i = 1/0;
Integer defaultResumeState = resumeServiceFeignClient.findDefaultResumeState(userId);
return defaultResumeState;
}
}
- 自定义兜底逻辑类
import com.alibaba.csp.sentinel.slots.block.BlockException;
public class SentinelHandlersClass {
// 整体要求和当时Hystrix一样,这里还需要在形参中添加BlockException参数,用于接收异常
// 注意:方法是静态的
public static Integer handleException(Long userId, BlockException blockException) {
return -100;
}
public static Integer handleError(Long userId) {
return -500;
}
}