最近公司服务器因为业务需要,需要经常改服务器的host,但是服务器不能重启,一般老说没有什么问题
但是出现了一个问题,修改host 没有起作用,老大这个给我说的,但是确定的修改hosts,一段时间,他是没有生效
于是重启,然后我们这边一步一步排查问题,
1,怀疑tomcat 设置dns 缓存(调用jvm缓存) 排除掉
2,httpclient,确定是这里的问题
httpclient 默认使用http 1.1,默认是用content:keey-Alive.(保持连接)
但是有一个问题,一般服务器不会返回 keep-aLive:5,(保持连接时间)
DefaultRequestDirector 293 httpClient 4.2
long duration = this.keepAliveStrategy.getKeepAliveDuration(response, context); if (this.log.isDebugEnabled()) { String s; if (duration > 0L) { s = "for " + duration + " " + TimeUnit.MILLISECONDS; } else { s = "indefinitely"; }
于是乎httpclient默认放回 -l(永不过期),一直缓存,然后又被放到连接池,继续使用
于是乎出现之前的问题
解决的问题:应为我们这边是后端,不涉及css,image 等资源,
所以就比较简单
复写 DefaultConnectionKeepAliveStrategy他的方法,设置keepAlive 合适的值
httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false)); DefaultConnectionKeepAliveStrategy defaultConnectionKeepAliveStrategy = new DefaultConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(HttpResponse response, HttpContext context) { long keepAlive = super.getKeepAliveDuration(response, context); if (keepAlive == -1) { keepAlive = 10; } return keepAlive; } }; httpClient.setKeepAliveStrategy(defaultConnectionKeepAliveStrategy);