本文節選自《瘋狂Spring Cloud微服務架構實戰》html
京東購買地址:https://item.jd.com/12256011.htmljava
噹噹網購買地址:http://product.dangdang.com/25201393.htmlgit
Spring Cloud教學視頻:https://my.oschina.net/JavaLaw/blog/1552993apache
Spring Cloud電子書:https://my.oschina.net/JavaLaw/blog/1570383架構
Feign使用一個Client接口來發送請求,默認狀況下,使用HttpURLConnection鏈接HTTP服務。與前面的編碼器相似,客戶端也採用了插件式設計,也就是說,咱們能夠實現本身的客戶端。本小節將使用HttpClient來實現一個簡單的Feign客戶端。爲pom.xml加入HttpClient的依賴:負載均衡
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency>
新建feign.Client接口的實現類,具體實現請見代碼清單5-13。微服務
代碼清單5-13:codes\05\5.2\feign-use\src\main\java\org\crazyit\feign\MyFeignClient.javaui
public class MyFeignClient implements Client { public Response execute(Request request, Options options) throws IOException { System.out.println("==== 這是自定義的Feign客戶端"); try { // 建立一個默認的客戶端 CloseableHttpClient httpclient = HttpClients.createDefault(); // 獲取調用的HTTP方法 final String method = request.method(); // 建立一個HttpClient的HttpRequest HttpRequestBase httpRequest = new HttpRequestBase() { public String getMethod() { return method; } }; // 設置請求地址 httpRequest.setURI(new URI(request.url())); // 執行請求,獲取響應 HttpResponse httpResponse = httpclient.execute(httpRequest); // 獲取響應的主體內容 byte[] body = EntityUtils.toByteArray(httpResponse.getEntity()); // 將HttpClient的響應對象轉換爲Feign的Response Response response = Response.builder() .body(body) .headers(new HashMap<String, Collection<String>>()) .status(httpResponse.getStatusLine().getStatusCode()) .build(); return response; } catch (Exception e) { throw new IOException(e); } } }
簡單講一下自定義Feign客戶端的實現過程,在實現execute方法時,將Feign的Request實例,轉換爲HttpClient的HttpRequestBase,再使用CloseableHttpClient來執行請求,獲得響應的HttpResponse實例後,再轉換爲Feign的Reponse實例返回。不只咱們實現的客戶端,包括Feign自帶的客戶端以及其餘擴展的客戶端,實際上就是一個對象轉換的過程。在運行類中直接使用咱們的自定義客戶端,請見代碼清單5-14。編碼
代碼清單5-14:codes\05\5.2\feign-use\src\main\java\org\crazyit\feign\MyClientTest.javaurl
public class MyClientTest { public static void main(String[] args) { // 獲取服務接口 PersonClient personClient = Feign.builder() .encoder(new GsonEncoder()) .client(new MyFeignClient()) .target(PersonClient.class, "http://localhost:8080/"); // 請求Hello World接口 String result = personClient.sayHello(); System.out.println(" 接口響應內容:" + result); } }
運行代碼清單5-14,輸出以下:
==== 這是自定義的Feign客戶端 接口響應內容:Hello World
注意:在本例的實現中,筆者簡化了實現,自定義的客戶端中並無轉換請求頭等信息,所以使用本例的客戶端,沒法請求其餘格式的服務。
雖然Feign也有HttpClient的實現,但本例的目的主要是向你們展現Feign客戶的原理。觸類旁通,若是咱們實現一個客戶端,在實現中調用Ribbon的API,來實現負載均衡的功能,是徹底能夠實現的。幸運的是,Feign已經幫咱們實現了RibbonClient,能夠直接使用,更進一步,Spring Cloud也實現本身的Client,咱們將在後面章節中講述。
本文節選自《瘋狂Spring Cloud微服務架構實戰》
Spring Cloud教學視頻:https://my.oschina.net/JavaLaw/blog/1552993
Spring Cloud電子書:https://my.oschina.net/JavaLaw/blog/1570383
本書代碼共享地址:https://gitee.com/yangenxiong/SpringCloud