標籤:style class blog code java http
閑來無事,將以前自己寫的一個庫放出來吧。。
有的時候會有這樣子的需求:
(1)伺服器A通過HTTP協議來訪問伺服器B
(2)伺服器A可能會並發的像B發送很多HTTP請求
類似於上述的需求,可能並不常見。。。因為在業務中確實遇到了這樣子的情境,所以就自己動手開發了一個庫。。。
實現原理:
(1)底層IO通過netty搞
(2)維護一個tcp的長串連池,這樣子就不用每次發送請求還要建立一個tcp串連了。。。
下面直接來看怎麼用吧:
(1)最常規的用法,向www.baidu.com發送100次get請求:
ClientPool pool = new NettyClientPool(2, "www.baidu.com"); pool.start(); for (int i = 0; i < 100; i++) { Request re = new Request("/", Request.RequestMethod.GET); pool.request(re).addListener(new Future.Listener() { @Override public void complete(Object arg) { Response res = (Response)arg; System.out.println(res.getBody().toString(Charset.forName("utf-8"))); } @Override public void exception(Throwable t) { } }); }
這裡可以看到,其實這裡是非同步提交的,所以需要註冊一些回調。。。
(2)使用同步的方式發送請求,這裡就弄成Post請求吧:
ClientPool pool = new NettyClientPool(2, "www.baidu.com"); pool.start(); Request re = new Request("/", Request.RequestMethod.POST); re.getBody().writeBytes("aaaa".getBytes(Charset.forName("utf-8"))); try { Response response = pool.requestWithTimeOut(re, 2000).sync(); System.out.println(response.getBody().toString(Charset.forName("utf-8"))); } catch (Throwable throwable) { System.out.println(throwable); } pool.stop();
這裡可以看到,提交請求的時候還帶有逾時的額,也就是2000毫秒都還沒有搞完,那麼就不搞了。。
好了,就介紹這些吧,反正post和get請求都有,支援逾時控制。。。
支援並發。。。至於說效能嘛。。。應該不差吧,也不知道該跟誰比較。。。。
、
最後給出github地址吧:
https://github.com/2225377fjs/HttpClientPool
點擊開啟連結