4

如何Spring Retry与外部调用集成AsyncRestTemplate?如果不可能,是否有另一个框架支持它?

我的用例:

public void doSomething() throws ExecutionException, InterruptedException {

    ListenableFuture<ResponseEntity<String>> future = asyncRestTemplate.getForEntity("http://localhost/foo", String.class);

    // do some tasks here

    ResponseEntity<String> stringResponseEntity = future.get(); // <-- How do you retry just this call?

}

你如何重试这个future.get()调用?如果外部服务返回 404,我想避免在两者之间再次调用这些任务,而只是重试外部调用?我不能只future.get()用 a包装,retryTemplate.execute()因为它实际上不会再次调用外部服务。

4

1 回答 1

0

您必须将整个doSomething(或至少模板操作和获取)包装在重试模板中。

编辑

您可以在未来get()添加 a而不是打电话;ListenableFutureCallback像这样的东西......

final AtomicReference<ListenableFuture<ResponseEntity<String>>> future = 
    new AtomicReference<>(asyncRestTemplate.getForEntity("http://localhost/foo", String.class));

final CountDownLatch latch = new CountDownLatch(1);
future.addCallback(new ListenableFutureCallback<String>() {

    int retries;

    @Override
    public void onSuccess(String result) {

         if (notTheResultIWant) {
             future.set(asyncTemplate.getFor (...));
             future.get().addCallback(this);    
             retries++;        
         }
         else {
              latch.countDown();
         }
    }

    @Override
    public void onFailure(Throwable ex) {
         latch.countDown();
    }

});


if (latch.await(10, Timeunit.SECONDS) {
    ...
    future.get().get();
}
于 2016-03-07T13:33:43.663 回答