RestTemplate遇上Hystrix
RestTemplate集成Hystrix和Robbin
查看RestTemplate源代码,可以看到RestTemplate继承了InterceptingHttpAccessor类,InterceptingHttpAccessor类通过ClientHttpRequestInterceptor接口提供了扩展功能。
实现intercept方法,在该方法中封装HystrixCommand和Ribbon逻辑即可。
下面的代码是集成了HystrixCommand的例子:
1 |
|
下面是集成了HystrixCommand和Ribbon的例子
1 |
|
2)RestTemplate支持Hystrix异步特性
Hystrix的执行在线程隔离模型下是支持异步的,因此也扩展一个RestTemplate异步执行。如下代码所示,通过调用queue()
方法返回一个Future。
1 | Future<String> fs = new CommandHelloWorld("World").queue(); |
这样可以修改RestOperations接口方法为异步方法:
从:
1 | <T> T getForObject(String url, Class<T> responseType, Object... uriVariables) throws RestClientException; |
到:
1 | <T> Future<T> getForObject(String url, Class<T> responseType, Object... uriVariables) throws RestClientException; |
然后在原生的RestTemplate做一层代理,在代理层集成Hystrix和Ribbon,无论是JDK动态代理还是硬编码实现代理都变得容易,然后就可以这样来调用了:
1 | HystrixAsyncRestOperations asyncRestTemplate =null; |