Tomcat Connector connectionTimeout含义和验证
Posted on Wed 28 April 2010 in 我用(IT)
1. Tomcat配置
今天小戚发出一封邮件,说因为线上系统中tomcat的连接超时(connectionTimeout)设置成60ms,造成第三方访问公司的服务,总是502异常。
这个设置在$tomcat/conf/server.xml中
<!-- Define a non-SSL HTTP/1.1 Connector on port 8080 -->
<Connector port="8080" maxHttpHeaderSize="8192"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="2000" disableUploadTimeout="true" />
2. 测试一下这个超时的含义
http://tomcat.apache.org/tomcat-5.5-doc/config/http.html
connectionTimeout :
- 单位是毫秒,Connector从接受连接到提交URI的等待的时间。
The number of milliseconds this Connector will wait, after accepting a connection, for the request URI line to be presented. The default value is 60000 (i.e. 60 seconds).
以上中文是经过如下分析过程得出的。
2.1. 是否是整个连接处理的时间?
写了一个servlet,doGet先sleep一段时间,再写一个输出,直接用浏览器访问。
经过测试,发现和这个时间无关。
2.2. 用HttpURLConnection做测试
写客户端模拟超时,可能是因为API直接实现到提交URI了,另外还怀疑底层有自动保持连接的动作,反正怎么Sleep都不超时,得换个写法了。
明天连上TCPMon看看后台有没有自动保持连接的动作。
def sURL="http://localhost:8080/index.jsp"
URL url = new URL(sURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
2.3. 用telnet收工测试
直接用telnet连上tomcat,如果什么都不输入,socket很快回断开,输入完整GET。。。,能够获得输出。如果不保持输入,则连接很快会断开。如果一直不停输入,连接继续保持。
$ telnet localhost 8080
GET /index.jsp HTTP/1.1
Accept-Language: zh-cn
Connection: Keep-Alive
Host: 192.168.0.53
Content-Length: 36
2.4. 直接写Socket做测试
还是2s超时,睡一秒能够正确获得输出,睡2秒,输出为空。
以下是Groovy代码
content ="""GET /index.jsp HTTP/1.1
Accept-Language: zh-cn
Connection: Keep-Alive
Host: 192.168.0.53
Content-Length: 36
"""
def sleepTime=1000
Socket socket = new Socket("localhost",8080)
println "is keep alive? " + socket.getKeepAlive()
println "sleep " + sleepTime + " ms."
Thread.sleep(sleepTime)
println "is closed? " + socket.isClosed()
println "sleep " + sleepTime + " ms."
//Thread.sleep(sleepTime)
println "write socket begin======"
writeStream(content, socket.getOutputStream())
println "read socket begin======"
println readStream(socket.getInputStream())[0..300]
void writeStream(content, stream) {
OutputStream buf = new BufferedOutputStream(stream);
OutputStreamWriter out = new OutputStreamWriter(buf, "UTF-8");
out.write(content)
out.flush();
print content
//out.close();
}
String readStream(stream){
String sResult=""
byte[] buffer = new byte[1024];
int readCount = stream.read(buffer);
while (readCount != -1) {
sResult += new String(buffer, 0,
readCount, "utf-8");
readCount = stream.read(buffer);
}
stream.close()
return sResult
}
用Groovy写测试代码真舒服,呵呵。