美文网首页
Spring Cloud Hystrix 忽略指定异常类型,不执

Spring Cloud Hystrix 忽略指定异常类型,不执

作者: zbsong | 来源:发表于2020-03-24 15:40 被阅读0次

    如果想忽略某个异常类型,不让这种异常执行降级逻辑,我们可以使用@HystrixCommand注解的ignoreExceptions参数实现

    还是使用上节创建的工程来实现本节的功能

    1.修改service方法

    @Service
    public class FallBackService {
    
        @Autowired
        private RestTemplate restTemplate;
    
        @HystrixCommand(fallbackMethod = "error")
        public String testFallBack(String name) {
            //String message = restTemplate.getForObject("http://hello-client/test_fallback?name={1}",String.class,name);
            //System.out.println(message);
            //让方法抛出ArithmeticException异常
            int i = 1/0;
            return "hello";
        }
    
        public String error(String name, Throwable e) {
            System.out.println(name + ": 出错啦出错啦" + e.getMessage());
            return "error";
        }
    
    }
    

    启动服务注册中、服务提供实例、消费服务实例
    访问请求:http://localhost:8000/fallback/test

    fallback-5.png
    可以看到所有请求都执行了服务降级逻辑,因为方法抛出了ArithmeticException异常,那么现在我们开始忽略掉ArithmeticException异常,不让ArithmeticException异常执行服务降级

    2.修改service,添加@HystrixCommand注解的ignoreExceptions参数,实现忽略
    ArithmeticException异常

    @Service
    public class FallBackService {
    
        @Autowired
        private RestTemplate restTemplate;
    
        @HystrixCommand(ignoreExceptions = {ArithmeticException.class}, fallbackMethod = "error")
        public String testFallBack(String name) {
            //String message = restTemplate.getForObject("http://hello-client/test_fallback?name={1}",String.class,name);
            //System.out.println(message);
            //抛出ArithmeticException异常
            int i = 1/0;
            return "hello";
        }
    
        public String error(String name) {
            System.out.println(name + ": 出错啦出错啦");
            return "error";
        }
    
    }
    
    再次请求: image.png

    可以看到没有执行服务降级逻辑,忽略掉了ArithmeticException异常。

    • 在fallback方法中加入Throwable,获取触发服务降级的具体内容,可以通过获取具体的异常来处理不同的逻辑
     public String error(String name, Throwable throwable) {
            System.out.println(name + ": 出错啦出错啦" + throwable);
            return "error";
        }
    
    执行请求: image.png

    相关文章

      网友评论

          本文标题:Spring Cloud Hystrix 忽略指定异常类型,不执

          本文链接:https://www.haomeiwen.com/subject/qnqbyhtx.html