springcloud alibaba sentinel降級 @SentinelResource

干饭达人GoodLucy發表於2024-08-09

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

相關文章