【震驚】Tomcat配置參數(shù)原來(lái)這么玩?99%的人不知道的秘密!
application.yml配置
server:
  port: 8081
  tomcat:
    maxThreads: 10
    maxConnections: 10
    acceptCount: 1  
    connectionTimeout: 3000測(cè)試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ù)與具體的請(qǐng)求響應(yīng)時(shí)間是沒(méi)有關(guān)系的。
測(cè)試2:
通過(guò)HttpURLConnection發(fā)送請(qǐng)求
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ù)與什么樣的客戶(hù)端做連接請(qǐng)求沒(méi)關(guān)系。
測(cè)試3:
通過(guò)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é)束了,也就是連接斷開(kāi)了。接著測(cè)試:
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(控制臺(tái)不停的輸入內(nèi)容):
圖片
程序一開(kāi)始運(yùn)行,控制臺(tái)不停地輸入內(nèi)容,發(fā)現(xiàn)程序一直正常,當(dāng)停留3秒后在輸入內(nèi)容,發(fā)現(xiàn)程序又?jǐn)嚅_(kāi)了。
結(jié)論:connectionTimeout參數(shù)是說(shuō)當(dāng)客戶(hù)端有服務(wù)器連接以后,如果客戶(hù)端不輸入任何內(nèi)容,那么超過(guò)了connectionTimeout設(shè)置的時(shí)間后連接會(huì)被斷開(kāi)。
完畢?。?!















 
 
 












 
 
 
 