日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java.lang.IllegalStateException: Connection pool shut down

發(fā)布時(shí)間:2023/12/1 编程问答 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java.lang.IllegalStateException: Connection pool shut down 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

最近使用HttpClient 4.5 使用?CloseableHttpClient 發(fā)起連接后,使用CloseableHttpResponse 接受返回結(jié)果,結(jié)果就報(bào)錯(cuò)了,上網(wǎng)查了下,有位stackoverflow的大兄弟說,只要將:

CloseableHttpClient httpClient = HttpClients.createDefault(); 改為: CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).setConnectionManagerShared(true).build();

就可以整正常執(zhí)行了,于是,用之,果然不報(bào)錯(cuò)了,但是為什么呢?以下是大兄弟的原文解釋:

I was having a similar error when I came across this thread and this seemed to fix the issue for me. I know this is an old question, but adding thoughts for others for future reference.

I'm not 100% sure as to why this fix works as the documentation around this is pretty awful. It was a lot of trial and error with what I was testing to get to this solution. From what I can

gather though, this fix works because it is then using a shared connection pool in the background, which means that connections remain open for use.

關(guān)鍵是最后一句話:大概意思是,后臺使用一個(gè)共享連接池,供剩下打開的連接去使用

?

原文地址:https://stackoverflow.com/questions/41744410/executorservice-performing-rest-requests

感謝下這位大兄弟

?

apache 官方的建議是,創(chuàng)建連接池,并為每一個(gè)接口URL分配一個(gè)線程,去執(zhí)行,還給出了許多高并發(fā)訪問的編碼技巧

原文:https://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html

那么,使用HttpClient 4.5連接池的正確姿勢是什么呢?

原作者地址:https://my.oschina.net/xlj44400/blog/711341

?

摘要: HttpClient 是 Apache Jakarta Common 下的子項(xiàng)目,可以用來提供高效的、最新的、功能豐富的支持 HTTP 協(xié)議的客戶端編程工具包,并且它支持 HTTP 協(xié)議最新的版本和建議

HttpClient簡介

HttpClient 是 Apache Jakarta Common 下的子項(xiàng)目,可以用來提供高效的、最新的、功能豐富的支持 HTTP 協(xié)議的客戶端編程工具包,并且它支持 HTTP 協(xié)議最新的版本和建議。HttpClient支持的功能如下:

  • 支持Http0.9、Http1.0和Http1.1協(xié)議。
  • 實(shí)現(xiàn)了Http全部的方法(GET,POST,PUT,HEAD 等)。
  • 支持HTTPS協(xié)議。
  • 支持代理服務(wù)器。
  • 提供安全認(rèn)證方案。
  • 提供連接池以便重用連接。
  • 連接管理器支持多線程應(yīng)用。支持設(shè)置最大連接數(shù),同時(shí)支持設(shè)置每個(gè)主機(jī)的最大連接數(shù),發(fā)現(xiàn)并關(guān)閉過期的連接。
  • 在http1.0和http1.1中利用KeepAlive保持長連接。

以前是commons-httpclient,后面被Apache HttpComponents取代,目前版本4.5.x,我們現(xiàn)在用的就是4.5版本

HttpClient連接池使用

為什么要用Http連接池:

1、降低延遲:如果不采用連接池,每次連接發(fā)起Http請求的時(shí)候都會(huì)重新建立TCP連接(經(jīng)歷3次握手),用完就會(huì)關(guān)閉連接(4次揮手),如果采用連接池則減少了這部分時(shí)間損耗2、支持更大的并發(fā):如果不采用連接池,每次連接都會(huì)打開一個(gè)端口,在大并發(fā)的情況下系統(tǒng)的端口資源很快就會(huì)被用完,導(dǎo)致無法建立新的連接
  • 默認(rèn)http協(xié)議:
private static final Charset CHAR_SET = Charset.forName("utf-8"); private static PoolingHttpClientConnectionManager cm;public void init() {cm = new PoolingHttpClientConnectionManager();cm.setMaxTotal(50);cm.setDefaultConnectionConfig(ConnectionConfig.custom().setCharset(CHAR_SET).build());SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(30000).setSoReuseAddress(true).build();cm.setDefaultSocketConfig(socketConfig);// HttpProtocolParams.setContentCharset(httpParams, "UTF-8");// HttpClientParams.setCookiePolicy(httpParams, "ignoreCookies");// HttpConnectionParams.setConnectionTimeout(httpParams, 30000);// HttpConnectionParams.setSoTimeout(httpParams, 30000);httpClient = HttpClientBuilder.create().setConnectionManager(cm).build();}public CloseableHttpClient getHttpClient() {int timeout=2;RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000) //設(shè)置連接超時(shí)時(shí)間,單位毫秒//.setConnectionRequestTimeout(timeout * 1000) //設(shè)置從connect Manager獲取Connection 超時(shí)時(shí)間,單位毫秒.setSocketTimeout(timeout * 1000).build(); //請求獲取數(shù)據(jù)的超時(shí)時(shí)間,單位毫秒CloseableHttpClient _httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(config).build();if(cm!=null&&cm.getTotalStats()!=null) { //打印連接池的狀態(tài) LOGGER.info("now client pool {}",cm.getTotalStats().toString());}return _httpClient;}public String post(String url, Map<String, String> params) {HttpPost post = new HttpPost(url);String resp = null;try {if(params != null){List<NameValuePair> nvps = new ArrayList<NameValuePair>();for (Map.Entry<String, String> param : params.entrySet()) {nvps.add(new BasicNameValuePair(param.getKey(), param.getValue()));}post.setEntity(new UrlEncodedFormEntity(nvps, CHAR_SET));}try {HttpResponse response = httpClient.execute(post);InputStream input = response.getEntity().getContent();resp = IOUtils.toString(input);} catch (ClientProtocolException e) {LOGGER.error(e.getMessage(), e);} catch (IOException e) {LOGGER.error(e.getMessage(), e);} catch (Exception e) {LOGGER.error(e.getMessage(), e);}} finally {if (post != null)post.releaseConnection();}return resp;}
  • https協(xié)議:
public class HttpConnectionManager {PoolingHttpClientConnectionManager cm = null;public void init() {LayeredConnectionSocketFactory sslsf = null;try {sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());} catch (NoSuchAlgorithmException e) {e.printStackTrace();}Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("https", sslsf).register("http", new PlainConnectionSocketFactory()).build();cm =new PoolingHttpClientConnectionManager(socketFactoryRegistry);cm.setMaxTotal(200);cm.setDefaultMaxPerRoute(20);}public CloseableHttpClient getHttpClient() { CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build(); /*//如果不采用連接池就是這種方式獲取連接CloseableHttpClient httpClient = HttpClients.createDefault();*/return httpClient;} }
  • httpClient使用
catch (Exception e) {logger.error("ufile send error e:",e);try {if (resEntity != null && resEntity.getContent() != null) {resEntity.getContent().close();}} catch (IllegalStateException | IOException e1) {logger.error("ufile send error e1:",e1);} finally {if (getMethod!=null) {getMethod.releaseConnection();}/*if (httpClient!=null) { //連接池使用的時(shí)候不能關(guān)閉連接,否則下次使用會(huì)拋異常 java.lang.IllegalStateException: Connection pool shut downtry {httpClient.close();} catch (IOException e2) {logger.error("ufile httpclient close error e2:",e2);}}*/}}
  • 連接池使用注意事項(xiàng):
    1. 連接池中連接都是在發(fā)起請求的時(shí)候建立,并且都是長連接2. HttpResponse input.close();作用就是將用完的連接釋放,下次請求可以復(fù)用,這里特別注意的是,如果不使用in.close();而僅僅使用httpClient.close();結(jié)果就是連接會(huì)被關(guān)閉,并且不能被復(fù)用,這樣就失去了采用連接池的意義。3. 連接池釋放連接的時(shí)候,并不會(huì)直接對TCP連接的狀態(tài)有任何改變,只是維護(hù)了兩個(gè)Set,leased和avaliabled,leased代表被占用的連接集合,avaliabled代表可用的連接的集合,釋放連接的時(shí)候僅僅是將連接從leased中remove掉了,并把連接放到avaliabled集合中

打印的狀態(tài):

INFO c.m.p.u.h.HttpClientUtils[72] - now client pool [leased: 0; pending: 0; available: 0; max: 50]

leased :the number of persistent connections tracked by the connection manager currently being used to execute requests. available :the number idle persistent connections. pending : the number of connection requests being blocked awaiting a free connection. max: the maximum number of allowed persistent connections.

HttpClient 4.5超時(shí)設(shè)置

4.5版本中,這兩個(gè)參數(shù)的設(shè)置都抽象到了RequestConfig中,由相應(yīng)的Builder構(gòu)建,具體的例子如下:

CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://stackoverflow.com/"); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(5000).setConnectionRequestTimeout(1000) .setSocketTimeout(5000).build(); httpGet.setConfig(requestConfig); CloseableHttpResponse response = httpclient.execute(httpGet); System.out.println("得到的結(jié)果:" + response.getStatusLine());//得到請求結(jié)果 HttpEntity entity = response.getEntity();//得到請求回來的數(shù)據(jù)
  • setConnectTimeout:設(shè)置連接超時(shí)時(shí)間,單位毫秒。ConnectTimeoutException
  • setConnectionRequestTimeout:設(shè)置從connect Manager獲取Connection 超時(shí)時(shí)間,單位毫秒。這個(gè)屬性是新加的屬性,因?yàn)槟壳鞍姹臼强梢怨蚕磉B接池的。ConnectionPoolTimeout
  • setSocketTimeout:請求獲取數(shù)據(jù)的超時(shí)時(shí)間,單位毫秒。 如果訪問一個(gè)接口,多少時(shí)間內(nèi)無法返回?cái)?shù)據(jù),就直接放棄此次調(diào)用。SocketTimeoutException
  • 上面3個(gè)時(shí)間4.5版本默認(rèn)是-1,就是不限,如果不設(shè)置就會(huì)一直等待

轉(zhuǎn)載于:https://www.cnblogs.com/Eillot/p/9042284.html

總結(jié)

以上是生活随笔為你收集整理的java.lang.IllegalStateException: Connection pool shut down的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。