sentinel熔断报java.lang.reflect.UndeclaredThrowableException

背景:内部要进行应用jdk&springboot升级,因此也需要将Spring Cloud Hystrix 替换成alibaba sentinel。

依赖

<dependency>
   <groupId>com.alibaba.cloud</groupId>
   <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
   <version>2022.0.0.0-RC2</version>
</dependency>

<dependency>
  <groupId>com.alibaba.csp</groupId>
  <artifactId>sentinel-datasource-nacos</artifactId>
  <version>1.8.6</version>
</dependency>

开启Feign对Sentinel的支持

sentinel官方文档

出现错误日志时的代码

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @Author: WeiXiang
 * @Desc:
 * @Date: Create in 5:09 PM on 2020/6/23.
 */
@FeignClient(value = "messageCenter", path = "/messageCenter/cloudService")
public interface JobApplyRest {

    /**
     * 获取用户最近的报名兼职list
     *
     * @desc:
     * @author: WeiXiang
     * @date: 9:04 PM 2020/6/23
     */
    @PostMapping("/userLastMonthApplyPartJob")
    String userLastMonthApplyPartJob(@RequestParam("userId") Long userId, @RequestParam("size") Integer size);
}

当达到熔断条件时,则抛出以下错误信息

错误被解决后的代码

解决方案:在FeignClient上,配置自定义fallback熔断降级处理方法

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @Author: WeiXiang
 * @Desc:
 * @Date: Create in 5:09 PM on 2020/6/23.
 */
@FeignClient(value = "messageCenter", path = "/messageCenter/cloudService", fallback = JobApplyRestFallback.class)
public interface JobApplyRest {

    /**
     * 获取用户最近的报名兼职list
     *
     * @desc:
     * @author: WeiXiang
     * @date: 9:04 PM 2020/6/23
     */
    @PostMapping("/userLastMonthApplyPartJob")
    String userLastMonthApplyPartJob(@RequestParam("userId") Long userId, @RequestParam("size") Integer size);
}

JobApplyRestFallback类

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @description: 报名单服务容错类
 * @author: jiusi
 * @create: 2023-09-01 10:23:47
 */
@Service
@Slf4j
public class JobApplyRestFallback implements JobApplyRest{
    @Override
    public String userLastMonthApplyPartJob(Long userId, Integer size) {
        log.warn("熔断降级开启JobApplyRest#userLastMonthApplyPartJob:userId:{}", userId);
        return null;
    }
}

 至此,java.lang.reflect.UndeclaredThrowableException 错误被解决。

问题原因:

sentinel通过代理实现熔断降级,当达到设置的阈值条件时,内部就抛出的自定义受检异常。但该受检异常并未在被代理对象接口定义中进行声明(即:Rest feignClient为被代理对象),那么这个异常就会被JVM包装成UndeclaredThrowableException进行抛出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值