美文网首页
Spring Cloud全解析:服务调用之Feign显示fall

Spring Cloud全解析:服务调用之Feign显示fall

作者: 墨线宝 | 来源:发表于2024-09-18 10:11 被阅读0次

    Feign显示fallback异常原因

    我在最一开始使用Feign的时候,是使用FallBack类去实现的FeignClient接口,就像这样

    @FeignClient(name = "SPRINGCLOUD2-PROVIDER",contextId = "DeptClient",
            fallback = DeptClient.DeptClientFallBack.class)
    public interface DeptClient {
    
        @GetMapping(value = "/dept/get/{id}")
        CommonResult<Dept> get(@PathVariable("id") long id);
    
        @GetMapping("/timeout")
        String timeout();
        
        @Component
        class DeptClientFallBack implements DeptClient{
    
            @Override
            public CommonResult<Dept> get(long id) {
                return null;
            }
    
            @Override
            public String timeout() {
                return null;
            }
        }
    }
    

    但是这样的话,我发现没有办法查看是因为什么原因造成的fallback呢,这种方法肯定是不行的

    然后发现@FeignClient注解中有一个属性是fallbackFactory,看着这个是有一个Throwable参数的,拿来试一试

    T create(Throwable cause);
    

    说干就干

    @FeignClient(name = "SPRINGCLOUD2-PROVIDER",contextId = "DeptClient",
            fallbackFactory = DeptClientFallBackFactory.class)
    public interface DeptClient {
    
        @GetMapping(value = "/dept/get/{id}")
        CommonResult<Dept> get(@PathVariable("id") long id);
    
        @GetMapping("/timeout")
        String timeout();
    }
    
    @Component
    public class DeptClientFallBackFactory implements FallbackFactory<DeptClient> {
    
        @Override
        public DeptClient create(Throwable throwable) {
            return new DeptClient() {
                @Override
                public CommonResult<Dept> get(long id) {
                    System.out.println("fallback 原因:"+throwable.getMessage());
                    CommonResult<Dept> result = new CommonResult<>();
                    result.isOk();
                    return result;
                }
    
                @Override
                public String timeout() {
                    return null;
                }
            };
        }
    }
    

    可以拿到异常信息了

    参考文献

    相关文章

      网友评论

          本文标题:Spring Cloud全解析:服务调用之Feign显示fall

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