connectionTimeout參數(shù)是說當(dāng)客戶端有服務(wù)器連接以后,如果客戶端不輸入任何內(nèi)容,那么超過了connectionTimeout設(shè)置的時(shí)間后連接會被斷開。
Application.yml配置
server:
port: 8081
Tomcat:
maxThreads: 10
maxConnections: 10
acceptCount: 1
connectionTimeout: 3000
測試1:
在controller中休眠10s>connectionTimeout
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/index")
public Object index() {
try {
System.out.println(Thread.currentThread().getName()) ;
TimeUnit.SECONDS.sleep(10) ;
} catch (InterruptedException e) {
e.printStackTrace();
}
return "success" ;
}
}
發(fā)現(xiàn)程序能正常地響應(yīng)。
結(jié)論:connectionTimeout參數(shù)與具體的請求響應(yīng)時(shí)間是沒有關(guān)系的。
測試2:
通過HttpURLConnection發(fā)送請求
public class HttpURLConnectionDemo {
public static void mAIn(String[] args) throws Exception {
HttpURLConnection con = (HttpURLConnection) new URL("http://localhost:8081/test/index").openConnection() ;
con.setDoInput(true) ;
con.setDoOutput(true) ;
long start = System.currentTimeMillis() ;
InputStream is = con.getInputStream() ;
Scanner scan = new Scanner(is) ;
while(scan.hasNext()) {
System.out.println("接收到內(nèi)容:" + scan.next() + "n耗時(shí):" + (System.currentTimeMillis() - start)) ;
}
scan.close() ;
con.disconnect() ;
con = null ;
}
}
結(jié)果:
圖片
結(jié)論:connectionTimeout參數(shù)與什么樣的客戶端做連接請求沒關(guān)系。
測試3:
通過Socket建立連接
public class TomcatConnectionTimeoutDemo {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("127.0.0.1", 8081) ;
long start = System.currentTimeMillis() ;
InputStream is = socket.getInputStream() ;
is.read() ;
System.out.println(System.currentTimeMillis() - start ) ;
}
}
運(yùn)行結(jié)果:
圖片
差不多3s后程序結(jié)束了,也就是連接斷開了。接著測試:
public class TomcatConnectionTimeoutDemo {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("127.0.0.1", 8081) ;
long start = System.currentTimeMillis() ;
final OutputStream os = socket.getOutputStream() ;
new Thread(() -> {
Scanner scan = new Scanner(System.in) ;
while(scan.hasNext()) {
String content = scan.next() ;
System.out.println("準(zhǔn)備發(fā)送:" + content) ;
try {
os.write(content.getBytes()) ;
os.flush() ;
} catch (IOException e) {
e.printStackTrace() ;
}
}
}).start() ;
InputStream is = socket.getInputStream() ;
is.read() ;
System.out.println(System.currentTimeMillis() - start ) ;
}
}
結(jié)果1(什么也不做):
圖片
結(jié)果2(控制臺不停的輸入內(nèi)容):
圖片
程序一開始運(yùn)行,控制臺不停地輸入內(nèi)容,發(fā)現(xiàn)程序一直正常,當(dāng)停留3秒后在輸入內(nèi)容,發(fā)現(xiàn)程序又?jǐn)嚅_了。
結(jié)論:connectionTimeout參數(shù)是說當(dāng)客戶端有服務(wù)器連接以后,如果客戶端不輸入任何內(nèi)容,那么超過了connectionTimeout設(shè)置的時(shí)間后連接會被斷開。
完畢!!!