通过回调到主请求实现外部服务的异步过程 - Spring [英] Implement Async process for external service with callback to main Request - Spring

查看:32
本文介绍了通过回调到主请求实现外部服务的异步过程 - Spring的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个设计问题需要解决使用 Spring 开发我的应用程序的位置.

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

有一个 REST API 必须按以下方式设计.

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

处理请求并调用外部网络服务并获得结果.

开始处理 -> 以异步方式调用外部 Web 服务.外部如果主请求是,服务将在完成后通知主请求还活着.-> 继续处理主要请求.-> 检查是否异步进程在接下来的 100 毫秒内完成 -> 如果结果到达,返回带有新 URI 的状态 201 以获得完整的结果.-> 如果外部服务未完成,返回状态 202 询问的 Client客户在一段时间后回电.

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.

更多更新:主线程在新线程中调用此 Web 服务.新线程一旦完成其处理,通知主线程是否还活着.否则只更新数据库中的数据.

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.

推荐答案

我是通过以下方式解决的.使用 CompletableFuture 执行异步任务,而不是 Springs 中的 @Async.

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

使用超时选项执行 future.get 以查看结果是否可用.如果没有,添加一个 future.thenAccept 子句来处理回调.

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

这篇关于通过回调到主请求实现外部服务的异步过程 - Spring的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆