Reputation: 123
In my application I need to implement functionality which ensure that if client makes GET request, application will hold this request until some change happen in database and also be possible to set maximal holding time. For example:
User makes GET request and request will hold for 20 seconds. If during these 20 s something changes in database, application release this request with required data, else application hold request for 20s.
I decide to use long polling. In my application I am using Spring Boot as well. Can you tell me if it possible do it with Spring or should I add some another library for that?
I also found Spring Scheluder for holding request for some interval, but problem is that, scheluder is not allowed for methods with parameters, but I need fetch data by specific user, so at least user's id should be passed. Also I am not sure if it possible to manually release this scheluder when it is needed.
Thanks for advice!
Upvotes: 3
Views: 7254
Reputation: 11
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.
Upvotes: 1