Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 950
Pasha Avatar asked Dec 09 '18 23:12

Pasha


People also ask

How is long polling implemented in Java?

So as per long polling, the client sends a request which is help by the server and the server responds to the request when an event occurs and then client sends a new request.

What is long polling in rest?

Long polling is a method that server applications use to hold a client connection until information becomes available. This is often used when a server must call a downstream service to get information and await a result.

How is long polling implemented?

In long polling the client polls the server continuously requesting new information. The server holds the request open until new data is available. Once available, the server responds and sends the new information.


1 Answers

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.

like image 177
GolamMazid Sajib Avatar answered Sep 26 '22 05:09

GolamMazid Sajib