Sentinel 自定义兜底逻辑

在上一篇文章自定义流控规则后,如果请求失败效果如下

在这里插入图片描述
这种错误提示不太友好,此时可以自定义兜底逻辑

@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;
    }

}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值