如何使用 AsyncRestTemplate
将 Spring Retry
与外部调用集成?如果不行,是否有其他框架支持?
我的用例:
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,我想避免再次调用这些任务并重试外部调用?我不能只用 retryTemplate.execute()
包装 future.get()
因为它实际上不会再次调用外部服务。
最佳答案
您必须将整个 doSomething
(或至少是模板操作和获取)包装在重试模板中。
编辑
您可以向 future 添加一个ListenableFutureCallback
,而不是调用get()
;像这样的……
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();
}
关于java - 如何将 Spring Retry 与 AsyncRestTemplate 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35836531/