简体   繁体   中英

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.

@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;

I don't understand why once I make the call and get the response it's not going inside my .isDone() block.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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