解决openfeign的fallback与springmvc注解冲突

kyaa111 2年前 ⋅ 710 阅读

@RequestMapping("/account")
public interface AccountFeign {

    @PostMapping("/test")
    String test();
}

@FeignClient(name = "${xxx.feign.basic}", contextId = "xxx", fallback = AccountFeignClientFallback.class)
public interface AccountFeignClient extends AccountFeign {

}

@Component
public interface AccountFeignClientFallback extends AccountFeignClient {

}

冲突原因简而言之就是实现了AccountFeignClient接口的AccountFeignClientFallback也被当成了openfeign的bean

解决方法

使用@FeignClient的fallbackFactory

@Component
public class AccountFeignFallbackFactory implements FallbackFactory<AccountFeignClient> {

    @Override
    public AccountFeignClient create(Throwable cause) {
        return new AccountFeignClient() {
            @Override
            public String test() {
                return "服务异常";
            }
        };
    }
}


@FeignClient(name = "${xxx.feign.basic}", contextId = "xxx", fallbackFactory = AccountFeignFallbackFactory.class)
public interface AccountFeignClient extends AccountFeign {

}