Spring - server.connection-timeout not working

前端 未结 3 915
猫巷女王i
猫巷女王i 2021-02-12 22:22

In my application.properties file I have...

server.port=8086
server.connection-timeout=15000

I know that the file is being loaded

3条回答
  •  逝去的感伤
    2021-02-12 22:57

    connection-timeout does not apply to long running requests. It does apply to the initial connection, when the server waits for the client to say something.

    Tomcat docs (not Spring Boot) define it as The number of milliseconds this Connector will wait, after accepting a connection, for the request URI line to be presented [...]

    To test the setting server.connection-timeout=4000 I connect using netcat and I don't send any HTTP request/headers. I get:

    $ time nc -vv localhost 1234
    Connection to localhost 1234 port [tcp/*] succeeded!
    
    real    0m4.015s
    user    0m0.000s
    sys     0m0.000s
    

    Alternatives

    1) Async

    From brightinventions.pl - Spring MVC Thread Pool Timeouts:

    In Spring MVC there is no way to configure a timeout unless you use async method. With async method one can use spring.mvc.async.request-timeout= to set amount of time (in milliseconds) before asynchronous request handling times out.

    I've set spring.mvc.async.request-timeout=4000 and I get a timeout in the browser with this:

    @GetMapping("/test-async")
    public Callable getFoobar() {
       return () -> {
          Thread.sleep(12000); //this will cause a timeout
          return "foobar";
       };
    }
    

    See Spring Boot REST API - request timeout?

    2) Servlet filter

    Another solution would be to use a servlet filter brightinventions.pl - Request timeouts in Spring MVC (Kotlin):

    override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain) {
        val completed = AtomicBoolean(false)
        val requestHandlingThread = Thread.currentThread()
        val timeout = timeoutsPool.schedule({
            if (completed.compareAndSet(false, true)) {
                requestHandlingThread.interrupt()
            }
        }, 5, TimeUnit.SECONDS)
    
        try {
            filterChain.doFilter(request, response)
            timeout.cancel(false)
        } finally {
            completed.set(true)
        }
    }
    

    3) Tomcat Stuck Thread Detection Valve?

    Tomcat has a Stuck Thread Detection Valve but I don't know if this can be configured programmatically using Spring Boot.

提交回复
热议问题