简体   繁体   English

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

[英]Spring Boot 2 Async making the call but not returning a response

I have my async half-way working. 我有一半的异步工作时间。 The call is being made async but when the result is returned it doesn't hit the code I have. 调用已异步进行,但返回结果时未达到我的代码。

Spring boot application class has @EnableAsync on it. 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);
    }
}

I've even tried another variation of my client response where I do: response = new AsyncResult<>(super.invoke(request, HttpMethod.POST)); return response; 我什至尝试了我的客户端响应的另一种变化: response = new AsyncResult<>(super.invoke(request, HttpMethod.POST)); return response; response = new AsyncResult<>(super.invoke(request, HttpMethod.POST)); return response;

I don't understand why once I make the call and get the response it's not going inside my .isDone() block. 我不明白为什么我一旦拨打电话并获得响应就不在我的.isDone()块内。

You have to wait until your request is done, like this: 您必须等到您的请求完成后,如下所示:

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

When you check the isDone result of the Future result it could be false, because your request is made asynchronously and it takes some time to make it. 当您检查Future结果的isDone结果时,它可能为false,因为您的请求是异步进行的,并且需要花费一些时间。

Just to note, the isDone method doesn't block the execution until the job is done, it just returns immediately whether your job is done or not. 请注意, isDone方法在作业完成之前不会阻塞执行,它只是立即返回您的作业是否完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM