javarestspring-mvcspring-bootlong-polling

How to implement Long Polling REST endpoint in Spring Boot app?


Would you be so kind as to share any up-to-date manual or explain here how to implement a REST Long Polling endpoint with the latest Spring (Spring Boot)?

Everything that I've found by this time is quite out-dated and was issued a couple of years ago.

So, I've raised a question is Long Polling still a good approach? I know it's used in chess.com


Solution

  • For long polling requests, you can use DeferredResult. When you return a DeferredResult response, the request thread will be free and the request will be handled by a worker thread. Here is one example:

    @GetMapping("/test")
    DeferredResult<String> test(){
        long timeOutInMilliSec = 100000L;
        String timeOutResp = "Time Out.";
        DeferredResult<String> deferredResult = new DeferredResult<>(timeOutInMilliSec, timeOutResp);
        CompletableFuture.runAsync(()->{
            try {
                //Long polling task; if task is not completed within 100s, timeout response returned for this request
                TimeUnit.SECONDS.sleep(10);
                //set result after completing task to return response to client
                deferredResult.setResult("Task Finished");
            }catch (Exception ex){
            }
        });
        return deferredResult;
    }
    

    This request demonstrates providing a response after waiting 10s. If you set sleep(100) or longer, you will get a timeout response.

    Check this out for more options.