如何将 Spring Retry 与 AsyncRestTemplate 集成

Gli*_*ide 5 java spring spring-retry spring-async

如何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?

}
Run Code Online (Sandbox Code Playgroud)

您如何重试此future.get()呼叫?如果外部服务返回 404,我想避免再次调用这些任务,而只是重试外部调用?我不能只future.get()用 a换行retryTemplate.execute(),因为它实际上不会再次调用外部服务。

Gar*_*ell 0

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

编辑

get()您可以ListenableFutureCallback在 future 中添加一个,而不是调用;像这样的东西...

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();
}
Run Code Online (Sandbox Code Playgroud)