use of org.apache.http.conn.ConnectTimeoutException in project ph-web by phax.
the class HttpClientRetryHandler method retryRequest.
public boolean retryRequest(final IOException aEx, final int nExecutionCount, final HttpContext aContext) {
if (nExecutionCount >= m_nMaxRetries) {
// Do not retry if over max retry count
return false;
}
// Check if exceptions make the retry unnecessary
if (m_eRetryMode.isCheckException()) {
if (aEx instanceof InterruptedIOException) {
// Timeout
return false;
}
if (aEx instanceof UnknownHostException) {
// Unknown host
return false;
}
if (aEx instanceof ConnectTimeoutException) {
// Connection refused
return false;
}
if (aEx instanceof SSLException) {
// SSL handshake exception
return false;
}
}
switch(m_eRetryMode) {
case RETRY_ALWAYS:
case RETRY_SMART:
return true;
case RETRY_IDEMPOTENT_ONLY:
final HttpClientContext aClientContext = HttpClientContext.adapt(aContext);
final HttpRequest aRequest = aClientContext.getRequest();
final boolean bIdempotent = !(aRequest instanceof HttpEntityEnclosingRequest);
if (bIdempotent) {
// (if it has no payload)
return true;
}
return false;
default:
throw new IllegalStateException("Unsupported retry mode: " + m_eRetryMode);
}
}
use of org.apache.http.conn.ConnectTimeoutException in project jplugin-v2 by sunlet.
the class HttpKit method initHttpClientBuilder.
private static HttpClientBuilder initHttpClientBuilder() {
int _maxConnections = Integer.parseInt(configMap.get(MAX_CONNECTIONS));
int _maxConnectionsPerRoute = Integer.parseInt(configMap.get(MAX_CONNECTIONS_PER_ROUTE));
int _connectTimeOut = Integer.parseInt(configMap.get(CONNECT_TIME_OUT));
int _connectionRequestTimeout = Integer.parseInt(configMap.get(CONNECTION_REQUEST_TIME_OUT));
int _socketTimeout = Integer.parseInt(configMap.get(SOCKET_TIME_OUT));
final HttpClientBuilder builder = HttpClientBuilder.create();
try {
// 请求配置
RequestConfig config = RequestConfig.custom().setConnectTimeout(_connectTimeOut * 1000).setConnectionRequestTimeout(_connectionRequestTimeout * 1000).setSocketTimeout(_socketTimeout * 1000).build();
builder.setDefaultRequestConfig(config);
// socket配置
SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true).build();
// 连接属性配置
ConnectionConfig connectionConfig = ConnectionConfig.custom().setCharset(UTF_8).setBufferSize(DEFAULT_SOCKET_BUFFER_SIZE).build();
// 请求重试处理
HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
if (executionCount >= maxRetries) {
// 如果已经重试指定次数了,就放弃
return false;
}
if (exception instanceof NoHttpResponseException) {
// 如果服务器丢掉了连接,那么就重试
return true;
}
if (exception instanceof SSLHandshakeException) {
// 不要重试SSL握手异常
return false;
}
if (exception instanceof ConnectTimeoutException) {
// 连接被拒绝
return false;
}
if (exception instanceof InterruptedIOException) {
// 超时
return false;
}
if (exception instanceof UnknownHostException) {
// 目标服务器不可达
return false;
}
if (exception instanceof SSLException) {
// SSL握手异常
return false;
}
HttpClientContext clientContext = HttpClientContext.adapt(context);
HttpRequest request = clientContext.getRequest();
// 如果请求是幂等的,就再次尝试
if (!(request instanceof HttpEntityEnclosingRequest)) {
return true;
}
return false;
}
};
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}).build();
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE)).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(_maxConnections);
cm.setDefaultMaxPerRoute(_maxConnectionsPerRoute);
cm.setDefaultSocketConfig(socketConfig);
cm.setDefaultConnectionConfig(connectionConfig);
builder.setConnectionManager(cm);
builder.setRetryHandler(httpRequestRetryHandler);
builder.setKeepAliveStrategy(myStrategy);
return builder;
} catch (Exception e) {
e.printStackTrace();
return builder;
}
}
use of org.apache.http.conn.ConnectTimeoutException in project WeChatPaySDK by baldLi.
the class WXPayRequest method request.
private String request(String urlSuffix, String uuid, String data, int connectTimeoutMs, int readTimeoutMs, boolean useCert, boolean autoReport) throws Exception {
Exception exception = null;
long elapsedTimeMillis = 0;
long startTimestampMs = WXPayV2Util.getCurrentTimestampMs();
boolean firstHasDnsErr = false;
boolean firstHasConnectTimeout = false;
boolean firstHasReadTimeout = false;
IWXPayDomain.DomainInfo domainInfo = config.getWXPayDomain().getDomain(config);
if (domainInfo == null) {
throw new Exception("WXPayConfig.getWXPayDomain().getDomain() is empty or null");
}
try {
String result = requestOnce(domainInfo.domain, urlSuffix, uuid, data, connectTimeoutMs, readTimeoutMs, useCert);
elapsedTimeMillis = WXPayV2Util.getCurrentTimestampMs() - startTimestampMs;
config.getWXPayDomain().report(domainInfo.domain, elapsedTimeMillis, null);
WXPayReport.getInstance(config).report(uuid, elapsedTimeMillis, domainInfo.domain, domainInfo.primaryDomain, connectTimeoutMs, readTimeoutMs, firstHasDnsErr, firstHasConnectTimeout, firstHasReadTimeout);
return result;
} catch (UnknownHostException ex) {
// dns 解析错误,或域名不存在
exception = ex;
firstHasDnsErr = true;
elapsedTimeMillis = WXPayV2Util.getCurrentTimestampMs() - startTimestampMs;
WXPayV2Util.getLogger().warn("UnknownHostException for domainInfo {}", domainInfo);
WXPayReport.getInstance(config).report(uuid, elapsedTimeMillis, domainInfo.domain, domainInfo.primaryDomain, connectTimeoutMs, readTimeoutMs, firstHasDnsErr, firstHasConnectTimeout, firstHasReadTimeout);
} catch (ConnectTimeoutException ex) {
exception = ex;
firstHasConnectTimeout = true;
elapsedTimeMillis = WXPayV2Util.getCurrentTimestampMs() - startTimestampMs;
WXPayV2Util.getLogger().warn("connect timeout happened for domainInfo {}", domainInfo);
WXPayReport.getInstance(config).report(uuid, elapsedTimeMillis, domainInfo.domain, domainInfo.primaryDomain, connectTimeoutMs, readTimeoutMs, firstHasDnsErr, firstHasConnectTimeout, firstHasReadTimeout);
} catch (SocketTimeoutException ex) {
exception = ex;
firstHasReadTimeout = true;
elapsedTimeMillis = WXPayV2Util.getCurrentTimestampMs() - startTimestampMs;
WXPayV2Util.getLogger().warn("timeout happened for domainInfo {}", domainInfo);
WXPayReport.getInstance(config).report(uuid, elapsedTimeMillis, domainInfo.domain, domainInfo.primaryDomain, connectTimeoutMs, readTimeoutMs, firstHasDnsErr, firstHasConnectTimeout, firstHasReadTimeout);
} catch (Exception ex) {
exception = ex;
elapsedTimeMillis = WXPayV2Util.getCurrentTimestampMs() - startTimestampMs;
WXPayReport.getInstance(config).report(uuid, elapsedTimeMillis, domainInfo.domain, domainInfo.primaryDomain, connectTimeoutMs, readTimeoutMs, firstHasDnsErr, firstHasConnectTimeout, firstHasReadTimeout);
}
config.getWXPayDomain().report(domainInfo.domain, elapsedTimeMillis, exception);
throw exception;
}
use of org.apache.http.conn.ConnectTimeoutException in project bboss-elastic by bbossgroups.
the class ElasticSearchRestClient method execute.
public String execute(final String entity, String options) throws ElasticSearchException {
String endpoint = BULK_ENDPOINT;
if (options != null) {
endpoint = new StringBuilder().append(endpoint).append("?").append(options).toString();
}
final ESStringResponseHandler responseHandler = new ESStringResponseHandler();
return _executeHttp(endpoint, responseHandler, new ExecuteRequest() {
@Override
public Object execute(ESAddress host, String url, int triesCount) throws Exception {
Object response = null;
if (showTemplate) {
if (logger.isInfoEnabled()) {
logger.info("ElasticSearch http request endpoint:{},retry:{},request body:\n{}", url, triesCount, entity);
}
}
response = restSeachExecutor.execute(url, entity, responseHandler);
return response;
}
});
/**
* int triesCount = 0;
* String response = null;
* Throwable e = null;
* ESAddress host = null;
* String url = null;
*
* while (true) {
*
* try {
* host = serversList.get(failAllContinue || !this.healthCheckEnabled());
* url = new StringBuilder().append(host.getAddress()).append( "/" ).append( endpoint).toString();
*
*// response = HttpRequestUtil.sendJsonBody(httpPool,entity, url, this.headers);
* if(this.showTemplate ){
* if(logger.isInfoEnabled()) {
* logger.info("ElasticSearch http request endpoint:{},retry:{},request body:\n{}",url,triesCount,entity);
* }
*
* }
* ESStringResponseHandler responseHandler = new ESStringResponseHandler();
* response = restSeachExecutor.execute(url,entity,responseHandler);
* e = getException( responseHandler );
* break;
* }
* catch (HttpHostConnectException ex) {
* host.setStatus(1);
* e = new NoServerElasticSearchException(ex);
* if (triesCount < serversList.size() - 1) {//失败尝试下一个地址
* triesCount++;
* continue;
* } else {
* break;
* }
*
* } catch (UnknownHostException ex) {
* host.setStatus(1);
* e = new NoServerElasticSearchException(ex);
* if (triesCount < serversList.size() - 1) {//失败尝试下一个地址
* triesCount++;
* continue;
* } else {
* break;
* }
*
* }
* catch (NoRouteToHostException ex) {
* host.setStatus(1);
* e = new NoServerElasticSearchException(ex);
* if (triesCount < serversList.size() - 1) {//失败尝试下一个地址
* triesCount++;
* continue;
* } else {
* break;
* }
*
* }
* catch (NoHttpResponseException ex) {
* host.setStatus(1);
* e = new NoServerElasticSearchException(ex);
* if (triesCount < serversList.size() - 1) {//失败尝试下一个地址
* triesCount++;
* continue;
* } else {
* break;
* }
*
* }
* catch (ConnectionPoolTimeoutException ex){//连接池获取connection超时,直接抛出
*
* e = handleConnectionPoolTimeOutException( ex);
* break;
* }
* catch (ConnectTimeoutException connectTimeoutException){
* host.setStatus(1);
* e = handleConnectionTimeOutException(connectTimeoutException);
* if (triesCount < serversList.size() - 1) {//失败尝试下一个地址
* triesCount++;
* continue;
* } else {
* break;
* }
* }
*// catch (IOException ex) {
*// host.setStatus(1);
*// if (triesCount < serversList.size()) {//失败尝试下一个地址
*// triesCount++;
*// e = ex;
*// continue;
*// } else {
*// e = ex;
*// break;
*// }
*//
*// }
* catch (SocketTimeoutException ex) {
* e = handleSocketTimeoutException( ex);
* break;
* }
* catch (NoServerElasticSearchException ex){
* e = ex;
*
* break;
* }
* catch (ClientProtocolException ex){
* host.setStatus(1);
* e = ex;
* if (triesCount < serversList.size() - 1) {//失败尝试下一个地址
* triesCount++;
* continue;
* } else {
* break;
* }
* //throw new ElasticSearchException(new StringBuilder().append("Request[").append(url).append("] handle failed: must use http/https protocol port such as 9200,do not use transport such as 9300.").toString(),ex);
* }
* catch (ElasticSearchException ex) {
* e = ex;
* break;
* }
* catch (Exception ex) {
* e = ex;
* break;
* }
* catch (Throwable ex) {
* e = ex;
* break;
* }
*
* }
* if (e != null){
* if(e instanceof ElasticSearchException)
* throw (ElasticSearchException)e;
* throw new ElasticSearchException(e);
* }
* return response;
*/
}
use of org.apache.http.conn.ConnectTimeoutException in project bboss-elastic by bbossgroups.
the class ElasticSearchRestClient method executeRequest.
public String executeRequest(String path, final String entity) throws ElasticSearchException {
final ESStringResponseHandler responseHandler = new ESStringResponseHandler();
return _executeHttp(path, responseHandler, new ExecuteRequest() {
@Override
public Object execute(ESAddress host, String url, int triesCount) throws Exception {
Object response = null;
if (showTemplate) {
if (logger.isInfoEnabled()) {
if (entity != null)
logger.info("ElasticSearch http request endpoint:{},retry:{},request body:\n{}", url, triesCount, entity);
else
logger.info("ElasticSearch http request endpoint:{},retry:{}", url, triesCount);
}
}
response = restSeachExecutor.executeSimpleRequest(url, entity, responseHandler);
return response;
}
});
/**
* int triesCount = 0;
* String response = null;
* Throwable e = null;
*
* ESAddress host = null;
* String url = null;
* while (true) {
*
* try {
* host = serversList.get(!healthCheckEnabled());
* url = getPath(host.getAddress(),path);
*// if (entity == null)
*// response = HttpRequestUtil.httpPostforString(url, null, this.headers);
*// else
*// response = HttpRequestUtil.sendJsonBody(entity, url, this.headers);
* if(this.showTemplate ){
* if(logger.isInfoEnabled()) {
* if(entity != null)
* logger.info("ElasticSearch http request endpoint:{},retry:{},request body:\n{}",url,triesCount,entity);
* else
* logger.info("ElasticSearch http request endpoint:{},retry:{}",url,triesCount);
* }
* }
* ESStringResponseHandler responseHandler = new ESStringResponseHandler();
* response = this.restSeachExecutor.executeSimpleRequest(url,entity,responseHandler);
* e = getException( responseHandler );
* break;
* }
*
* catch (HttpHostConnectException ex) {
* host.setStatus(1);
* e = new NoServerElasticSearchException(ex);
* if (triesCount < serversList.size() - 1) {//失败尝试下一个地址
* triesCount++;
* continue;
* } else {
* break;
* }
*
* } catch (UnknownHostException ex) {
* host.setStatus(1);
* e = new NoServerElasticSearchException(ex);
* if (triesCount < serversList.size() - 1) {//失败尝试下一个地址
* triesCount++;
* continue;
* } else {
* break;
* }
*
* }
* catch (NoRouteToHostException ex) {
* host.setStatus(1);
* e = new NoServerElasticSearchException(ex);
* if (triesCount < serversList.size() - 1) {//失败尝试下一个地址
* triesCount++;
* continue;
* } else {
* break;
* }
*
* }
*
* catch (NoHttpResponseException ex) {
* host.setStatus(1);
* e = new NoServerElasticSearchException(ex);
* if (triesCount < serversList.size() - 1) {//失败尝试下一个地址
* triesCount++;
* continue;
* } else {
* break;
* }
*
* }
* catch (ConnectionPoolTimeoutException ex){//连接池获取connection超时,直接抛出
*
* e = handleConnectionPoolTimeOutException( ex);
* break;
* }
* catch (ConnectTimeoutException connectTimeoutException){
* host.setStatus(1);
* e = handleConnectionTimeOutException(connectTimeoutException);
* if (triesCount < serversList.size() - 1) {//失败尝试下一个地址
* triesCount++;
* continue;
* } else {
* break;
* }
* }
*// catch (IOException ex) {
*// host.setStatus(1);
*// if (triesCount < serversList.size()) {//失败尝试下一个地址
*// triesCount++;
*// e = ex;
*// continue;
*// } else {
*// e = ex;
*// break;
*// }
*//
*// }
* catch (SocketTimeoutException ex) {
* e = handleSocketTimeoutException( ex);
* break;
* }
* catch (NoServerElasticSearchException ex){
* e = ex;
* break;
* }
* catch (ClientProtocolException ex){
* host.setStatus(1);
* e = ex;
* if (triesCount < serversList.size() - 1) {//失败尝试下一个地址
* triesCount++;
* continue;
* } else {
* break;
* }
*// throw new ElasticSearchException(new StringBuilder().append("Request[").append(url).append("] handle failed: must use http/https protocol port such as 9200,do not use transport such as 9300.").toString(),ex);
* }
* catch (ElasticSearchException ex) {
* throw ex;
* }
*
* catch (Exception ex) {
* e = ex;
* break;
* }
* catch (Throwable ex) {
* e = ex;
* break;
* }
* }
* if (e != null){
* throw new ElasticSearchException(e);
* }
* return response;
*/
}
Aggregations