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

Pasha picture Pasha · Dec 10, 2018 · Viewed 14.2k times · Source

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

Answer

GolamMazid Sajib picture GolamMazid Sajib · Dec 10, 2018

For long pulling request you can use DeferredResult. when you return DeferredResult response, request thread will be free and this request handle by 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 pooling task;If task is not completed within 100 sec timeout response retrun 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;
    }

In this request give response after waiting 10 sec. if you wait more than 100 sec you will get timeout response.

Look at this.