Implement Async process for external service with

2019-09-01 05:23发布

问题:

I have a design problem to solve where my application is developed using Spring.

There is a REST API which have to be designed in the following way.

Process request and call an external web service and get the results.

Start processing -> Call External Web Service in async way. External service will inform main request once completes if main request is still alive. -> Continue to process main request. -> Check if async process completes in next 100millisec -> If results arrived, return Status 201 with new URI to get complete results. -> If external service is not complete, return Client with Status 202 asking client to call back after some time.

I am thinking on how to achieve this solution.

I know we might have many solutions. But can I have some good approach/suggestions in achieving this? Not very detailed.

Please let me know if you need any more details on this if it is not clear.

More updates: Main thread calls this web service in a new thread. New thread once completes its processing, informs main thread if alive. Otherwise just updates data in db.

回答1:

I solved it in the following way. Use CompletableFuture to execute the async task instead of @Async from Springs.

Do future.get with a timeout option to see if the results are available. If not, add a future.thenAccept clause to handle callback.