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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With