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

时间:2018-12-07 15:26:03

标签: java spring-boot asynchronous

我正在异步进行中途工作。该调用正在进行异步处理,但是返回结果时,它并没有符合我的代码。

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()区块内。

1 个答案:

答案 0 :(得分:0)

您必须等到请求完成后,像这样:

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

当您检查isDone结果的Future结果时,它可能是错误的,因为您的请求是异步进行的,并且需要花费一些时间。

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