3

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!

royalghost
  • 2,773
  • 5
  • 23
  • 29
Joe Grizz
  • 113
  • 2
  • 11
  • You probably should consider SSE or WebSockets, so the server notifies the clients when the work is done. Since long polling adds a lot of HTTP overhead – rena Mar 28 '18 at 16:27
  • Heavily related: https://stackoverflow.com/q/31458910/1079354 – Makoto Mar 28 '18 at 16:36
  • Usually the client but not the server decides on how long she is eager to wait on a response from the server or disconnects due to no response hence I'm not sure if HTTP is the right protocol in your case then – Roman Vottner Mar 28 '18 at 17:11
  • @RomanVottner so what protocol do you recommend? – Joe Grizz Mar 28 '18 at 19:07
  • @Scheduled is not used for processing requests. It is used like an internal crontab functionality for your application, to run adhoc work like cleaning u cache or refreshing an OAuth token. – Jose Martinez Mar 29 '18 at 12:04

1 Answers1

1

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.

Davies
  • 11
  • 1