英文:
Java future, promise or?
问题
我有以下情况。
- 用户从我的服务请求某些信息。但是,我没有这些信息,必须从第三方网站请求。
- 我向第三方网站发出请求(POST)。第三方网站(我无法控制)在我的初始POST中期望一个回调URL,而不是直接提供信息。因此,我请求信息的请求会立即返回,但没有信息。
- 当信息准备好时,第三方网站通过初始POST的回调URL调用我的服务,并提供信息(通过POST)。
- 然后,我想将信息返回给用户。
问题是,我希望在通过回调获取信息之前,阻塞原始用户的信息请求。我不确定应该如何在Java中编写它。我正在使用Spring Boot(虽然我不确定它有多相关)。我还在考虑将其编码为普通的Spring Boot MVC应用程序或反应式的Spring Boot应用程序(我想使用后者,但我仍在学习有关反应式Spring Boot的知识)。无论如何,我都对这两种框架的解决方案都感兴趣。
基本问题是,如何在第三方网站将信息通过回调URL发送给我之前,阻塞最初的用户信息请求?我已经看过有关Futures和Promises的内容,但要么我对它们的理解不够透彻,要么它们不是我在寻找的解决方法。
有什么建议吗?提前谢谢。
英文:
I have the following scenario.
- A user requests some information from my service. However, I don't have the information and have to request it from a third party site.
- I make the request (a POST) to the third party site. Rather than providing the information directly, the third part site (which I don't control) expects a callback url in my initial post. So, the request I make for the information returns immediately, but without the information.
- When the information is ready, the third party site calls my service via the callback url (from my initial POST) and provides the information (via a POST).
- I then want to return the information to the user.
The issue is that I want to block on the original user's request for information until I get the information back via the callback. I'm not sure how I should code that it in java. I'm using spring boot (though I'm not sure how relevant that is). I'm also looking at coding that either as a normal spring boot mvc app or a reactive spring boot app (I'd like to do the latter, but I'm still learning about reactive spring boot). Regardless, I'd be interested in solutions for either framework.
The basic question is how do I block on the initial user information request until the third party site sends the information to the callback url? I've looked at futures and promises and either I don't really understand them or they aren't the droids I'm looking for.
Any suggestions? Thanks in advance.
答案1
得分: 1
如果您希望在等待第三方的回复时阻塞线程,这将是对资源的无谓浪费。您需要准备一个包含用户请求所有信息的对象,并为其分配一个唯一的标识符,然后向第三方发送带有包含该标识符的回调URL的请求,例如 http://myservice.org/callback?id=123
。启动一个服务器来接受这些回调。该服务器从URL提取标识符,从哈希映射中查找具有此标识符的用户请求对象,并发送回复。
英文:
If you want to block a thread while waiting the reply from third party, this is useless wasting of resources. You need to prepare an object with all the information about the user's request and assign a uniqe id to it, and to send request to the third party with callback url containing that id, like http://myservice.org/callback?id=123
. Start a server to accept that callbacks. That server extracts id from url, finds the user request object with this id from hashmap, and sends the reply.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论