springcloud alibaba sentinel降级 @SentinelResource

1. sentinel降级方法和主方法 public 且 返回值、参数 必须一致的情况下,必须加【BlockException blockException】参数

2、业务降级方法和主方法 public 且 返回值、参数 必须一致,Throwable参数可加可不加

@RequestMapping("/consumer/fallback/{id}")
@SentinelResource(value = "orderFallback",
        fallback = "businessEx",
        blockHandler = "sentinelEx",
        exceptionsToIgnore = {IllegalArgumentException.class})
public CommonResult<Payment> fallback(@PathVariable Long id) {
    CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id,
            CommonResult.class, id);
    if (id == 4) {
        throw new IllegalArgumentException("【不受任何降级异常管控,走正常java异常】");
    }
    if (result.getData() == null) {
        throw new NullPointerException("该ID没有对应记录,空指针异常");
    }
    return result;
}

//sentinel 熔断限流异常
public CommonResult<Payment> sentinelEx(Long id, BlockException blockException) {
    Payment payment = new Payment(id, "null");
    return new CommonResult<>(445, "【sentinel降级异常】" + blockException.getMessage(), payment);
}

//业务异常
public CommonResult<Payment> businessEx(Long id, Throwable e) {
    Payment payment = new Payment(id, "null");
    return new CommonResult<>(505, "【业务降级异常】"
            + e.getMessage(), payment);
}
posted @ 2024-08-09 12:38  干饭达人GoodLucy  阅读(15)  评论(0编辑  收藏  举报