Feign对Hystrix的支持

   达到效果:

  1. 调用外部rest接口,而不是通过服务名调用;
  2. 实现Hystrix效果;

 

   以调用云片接口为例,完整示例代码:

 

@FeignClient(name = "yunpian", url = "https://sms.yunpian.com/v2",
        fallback = YunpianClient.YunpianFallback.class,
        fallbackFactory = YunpianClient.YunpianFallbackFactory.class)
public interface YunpianClient {

    @RequestMapping(value = "/sms/single_send.json", method = RequestMethod.POST,
            headers = {"Accept=application/json;charset=utf-8;", "Content-Type=application/x-www-form-urlencoded;charset=utf-8;"})
    Object singleSend(@RequestParam("apikey") String apikey,
                             @RequestParam("text") String text,
                             @RequestParam("mobile") String mobile);

    @Component
    class YunpianFallback extends BaseClient implements YunpianClient{

        @Override
        public Object singleSend(String apikey,
                                 String text,
                                 String mobile) {
            logger.error("调用异常,进入fallback ...,参数:{}, {}, {}", apikey, text, mobile);
            return "YunpianFallback ....";
        }
    }

    @Component
    class YunpianFallbackFactory extends BaseClient implements FallbackFactory {

        @Override
        public YunpianClient create(Throwable throwable) {
            return new YunpianClient() {
                @Override
                public Object singleSend(@RequestParam("apikey") String apikey, @RequestParam("text") String text, @RequestParam("mobile") String mobile) {
                    logger.error("调用异常,FallbackFactory ...,参数:{}, {}, {}", apikey, text, mobile);
                    return "FallbackFactory ....";
                }
            };
        }
    }
}

 

利用@FeignClient可很方便调用外部rest接口,并实现Hystrix效果。

 

但在上面代码中,只有fallback生效,fallbackFactory并不会被执行,看效果fallback 和 fallbackFactory只需配置一个即可。

 

 

你可能感兴趣的:(spring,cloud)