gpt4 book ai didi

java - Spring Boot 2异步进行调用但不返回响应

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:43 25 4
gpt4 key购买 nike

我的异步工作正在进行中。该调用是异步的,但是当返回结果时,它没有命中我的代码。

Spring boot应用程序类有 @EnableAsync就在上面。

@Service
public class MyService() {

private MyClient client;

@Autowired
public MyService(MyClient client) {
this.client = client;
}

public String callHttpService() {
Future<String> asyncResponse = client.submitOrder("test");

String response = null;

if(asyncResponse.isDone()) {

// client call made and result comes back but never comes in here
response = asyncResponse.get();
}

return response;
}
}

@Component
public class MyClient() extends RestClient {

@Async
public Future<String> submitOrder(String request) {
String response;
try {
response = super.invoke(request, HttpMethod.POST);
} catch(RestInvocationException e) {
.....
}

return new AsycResult<>(response);
}
}

我什至尝试了客户响应的另一种变体:response = new AsyncResult<>(super.invoke(request, HttpMethod.POST)); return response;

我不明白为什么一旦我调用电话并得到回复,它就不会进入我的.isDone() block 。

最佳答案

您必须等待请求完成,如下所示:

while (true) {
if (asyncResponse.isDone()) {
response = asyncResponse.get();
break;
}
Thread.sleep(1000);
}

当您检查 Future 结果的 isDone 结果时,它可能为 false,因为您的请求是异步发出的,需要一些时间才能发出。

请注意,isDone 方法在作业完成之前不会阻止执行,它只是立即返回,无论您的作业是否完成。

关于java - Spring Boot 2异步进行调用但不返回响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53672430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com