【发布时间】:2026-01-27 09:45:01
【问题描述】:
我有 2 个 API(doGET 和 doPOST),我正在尝试使用异步机制让 doPOST 为 doGET 请求写入 httpServletResponse。
我的控制流程 -
- 客户端发出 requestA (getData) 调用
- Java 服务器进行一些处理并调用外部环境 3rd 方 API
- 第 3 方 API 不返回响应但调用我的另一个端点 doPOST
- doPOST 现在需要将 httpServletResponse 的对象写入 doGET
- doGET 在 doPOST 完成后立即返回此对象。
为了解决这个问题,我发现我可以在java中使用一些异步编程机制,比如CompletableFuture。但是我对如何在我的代码中准确设置这个机制感到困惑。这是我到目前为止所做的 -
doGET
public void doGET(HttpServletRequest request, HttpServletResponse response) {
// some processing
// Call 3rd Party API
CompletableFuture<HttpServletRequest> completableFuture = CompletableFuture.supplyAsync(() -> doPOST());
while (!completableFuture.isDone()) {
System.out.println("CompletableFuture is not finished yet...");
}
HttpServletRequest result = completableFuture.get();
response = result;
}
我无法弄清楚如何为此设置 completableFuture。在这里需要帮助。
doPOST
public HttpServletResponse doPOST(HttpServletRequest request, HttpServletResponse response) {
// receive 3rd party request
// add data from 3rd party request into a new response object
// add response object into hashmap
}
我怎样才能正确地完成这项工作?
【问题讨论】:
-
您需要 doPost 中 3rd Party Api 的响应吗?
-
我不确定您是否真的想在循环中打印“CompletableFuture 尚未完成”,这将使 JVM 可能会打印数千次相同的消息而根本没有实用程序。相反,只需调用 .get() 它将等待 Future 完成,然后再继续执行。
-
如果步骤的执行顺序相互依赖,那么使用可完成的未来没有好处。但是如果有一些步骤是不相互依赖的,你可以得到使用completable future的好处。
-
@Pirate 3rd 方 API 请求是一个 POST 请求。所以我只需要向该请求发送 200 OK,然后 doPOST 将执行 doGET 响应的写入。
-
查看您的 doPost 是否依赖于第 3 方响应。这里的response不仅是响应体,还有api返回的状态码。在这种情况下,两个 api 相互依赖,因此您不会从使用 completable future 中获得任何好处。
标签: java asynchronous completable-future