Home > Software design >  Spring Boot How to Cancel API Request After Sometime
Spring Boot How to Cancel API Request After Sometime

Time:11-08

I have API exposed which sends a data to some other application, currently my code look like this :

     @PostMapping("/run/}")
        public ResponseEntity<Void>  runQuery(@PathVariable String timeToRun) {
              
                      for(int i = 0 ; i < timeToRun ; i  ) {
                          // Do some logic
}
                    
        }

Let say i have 10 API request comes simultaneously, with different timeToRun parameters after sometime lets say 2 users want to stop their API request execution i.e stop runQuery method for those users, how i can maintain the state and how i can stop those 2 API request.

CodePudding user response:

In case you want to have it like a loop until the timeToRun is reached, you can do the following:

  1. Either create a Map<String, JobObject> or store the job information directly in DB (this will allow you to have a clear state even if the server is stopped)
  2. Instead of void, generate a unique identifier for each request, update the state of your store (Map or DB), and return it to the client.
  3. Client should poll for the status of the job -> new endpoint that accepts job identifier required
  4. Create a new endpoint for cancellation -> it should accept the job identifier and should do the logic of breaking the loop

The responsibility of job execution should be taken by Thread pool executors. Check this article for reference: https://www.baeldung.com/thread-pool-java-and-guava.

CodePudding user response:

I think, we need a bit more understanding here. When you say after some time, you want to stop the execution for two apis,

  1. how will you identify which apis and when to stop, looks like you would need another param there.

Impl logic,

  • Run each logic in a separate thread, and kill the thread, when you want
  • Related