代码之家  ›  专栏  ›  技术社区  ›  Justin

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

  •  1
  • Justin  · 技术社区  · 6 年前

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

    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 回复  |  直到 6 年前
        1
  •  0
  •   Stanislav    6 年前

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

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

    当你检查 isDone 结果 Future 结果可能是错误的,因为您的请求是异步发出的,并且发出请求需要一些时间。

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