Sentinel @SentinelResource注解非接口方法限流和降级

一、Controller

@RestController
@RequestMapping("/test/")
public class TestController {

    @Autowired
    private TestService testService;

    @RequestMapping("test")
    public String test() {
        String str = testService.findByName("test");
        return str;
    }

    @RequestMapping("test_fall")
    public String testFall() {
        String str = testService.findByName2("test_fall");
        return str;
    }


    @RequestMapping("test2")
    public String test2() {
        return "test2";
    }
}

二、Service

@Service
@Slf4j
public class TestServiceImpl implements TestService {

    // 记录访问次数
    private int count = 0;

    /**
     * 限流
     * @param str
     * @return
     */
    @SentinelResource(value = "findByName", blockHandler = "findByNameBlockHandler")
    @Override
    public String findByName(String str) {
        return "findByName: " + str;
    }
    public String findByNameBlockHandler(String str, BlockException blockException) {
        return "限流成功";
    }

    /**
     * 降级
     * @param str
     * @return
     */
    @SentinelResource(value = "findByName2", fallback = "findByNameFallback")
    @Override
    public String findByName2(String str) {
        // 保证count为奇数时异常,偶数时不异常
        if ((count++ & 1) == 1) {
            throw new RuntimeException("人为制造异常");
        } else {
            return str;
        }
    }
    public String findByNameFallback(String str, Throwable throwable) {
        if (throwable instanceof RuntimeException) {
            log.error("访问失败,原因是:" + throwable.getMessage());
            return "访问失败,原因是:" + throwable.getMessage();
        } else if (throwable instanceof DegradeException) {
            DegradeException e = (DegradeException) throwable;
            DegradeRule rule = e.getRule();
            int time = rule.getTimeWindow();
            log.error("访问被降级,预计[" + time + "]秒内无法访问");
            return "访问被降级,预计[" + time + "]秒内无法访问";
        } else {
            return str;
        }
    }
}

三、限流

  •  @SentinelResource的value,即为nacos中配置的source。
  • blockHandler为限流抛出异常实现处理函数,该函数的传参必须与资源点的传参一样,并且最后加上BlockException异常参数;同时,返回类型也必须一样。

nacos配置:

[
    {
        "resource": "findByName",
        "limitApp": "default",
        "grade": 1,
        "count": 2,
        "strategy": 0,
        "controlBehavior": 0,
        "clusterMode": false
    }
]

三、断流降级

  •  @SentinelResource的value,即为nacos中配置的source。
  • fallback为降级抛出异常实现处理函数,该函数的传参必须与资源点的传参一样,同时返回类型也必须一样。可以额外选填一个 Throwable 类型的参数用于接收对应的异常。

 

快速访问:http://localhost:9010/test/test_fall

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值