怎样解决httpclient中出现NoHttpResponseException异常

本文针对HTTP客户端出现NoHttpResponseException的问题提供了详细的解决方案。该异常通常发生在服务器负载过高时,导致无法处理请求的情况。文中通过定制化的CloseableHttpClient配置,实现特定异常情况下的自动重试机制,有效提高了系统的稳定性和可用性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载地址: https://www.2cto.com/kf/201710/688548.html


httpclient版本:4.5.2

在项目实际运行中,偶发异常:org.apache.http.NoHttpResponseException。

官网解释是:

In some circumstances, usually when under heavy load, the web server may be able to receive requests but unable to process them. A lack of sufficient resources like worker threads is a good example. This may cause the server to drop the connection to the client without giving any response. HttpClient throws NoHttpResponseException when it encounters such a condition. In most cases it is safe to retry a method that failed with NoHttpResponseException.


修改方案:

CloseableHttpClient httpClient = HttpClients.custom()
    .setDefaultRequestConfig(config)
    .setConnectionManager(getPoolManager())
 
    //不使用这种方式,不方便看日志,使用下面自定义的retry
//  .setRetryHandler(new DefaultHttpRequestRetryHandler(3,true))
 
    .setRetryHandler((exception, executionCount, context) -> {
        if (executionCount > 3) {
            log.warn("Maximum tries reached for client http pool ");
            return false;
        }
 
        if (exception instanceof NoHttpResponseException     //NoHttpResponseException 重试
                || exception instanceof ConnectTimeoutException //连接超时重试
//              || exception instanceof SocketTimeoutException    //响应超时不重试,避免造成业务数据不一致
                ) {
            log.warn("NoHttpResponseException on " + executionCount + " call");
            return true;
        }
        return false;
    })
    .build();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值