欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  网络运营

Sentinel整合Ribbon做服务熔断

程序员文章站 2022-06-10 13:48:29
搭建两个服务提供者9003和9004搭建一个服务调用这84启动nacos和Sentinel调用者核心代码public static final String SERVICE_URL = "http://nacos-payment-provider"; @Resource private RestTemplate restTemplate; @RequestMapping("/consumer/fallback/{id}") //@SentinelResou...

搭建两个服务提供者
9003和9004
搭建一个服务调用这
84
启动nacos和Sentinel
调用者核心代码

public static final String SERVICE_URL = "http://nacos-payment-provider";

    @Resource
    private RestTemplate restTemplate;



    @RequestMapping("/consumer/fallback/{id}")
    //@SentinelResource(value = "fallback") //没有配置
    //@SentinelResource(value = "fallback",fallback = "handlerFallback") //fallback只负责业务异常
    //@SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler只负责sentinel控制台配置违规
    @SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler"/*, exceptionsToIgnore = {IllegalArgumentException.class}*/)
    //若blockHandler和fallback都进行了配置,则被限流降级而抛出BlockException时只会进入blockHandler中处理逻辑
    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 ("IllegalArgumentException,非法参数异常....");
        }else if (result.getData() == null) {
            throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
        }

        return result;
    }

    //fallback
    public CommonResult handlerFallback(@PathVariable  Long id,Throwable e) {
        Payment payment = new Payment(id,"null");
        return new CommonResult<>(444,"兜底异常handlerFallback,exception内容  "+e.getMessage(),payment);
    }

    //blockHandler
    public CommonResult blockHandler(@PathVariable  Long id,BlockException blockException) {
        Payment payment = new Payment(id,"null");
        return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException  "+blockException.getMessage(),payment);
    }

这里服务熔断主要也就是@SentinelResource注解的配置,单配fallback和blockHandler是很好理解的,但是两个都配置的情况S下,Sentinel也做了降级处理的情况下那么只会进入blockHandler中处理逻辑

本文地址:https://blog.csdn.net/CSDN877425287/article/details/111993590

相关标签: 微服务