[英]How to integrate Spring Retry with AsyncRestTemplate
How can you integrate Spring Retry
with external calls with AsyncRestTemplate
? 如何使用
AsyncRestTemplate
将Spring Retry
与外部调用集成? If it's not possible, is there another framework that supports it? 如果不可能,是否有另一个支持它的框架?
My use case: 我的用例:
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?
}
How do you retry this future.get()
call? 你如何重试这个
future.get()
调用? If the external service returns a 404, I want to avoid calling those tasks in between again and just retry the external call? 如果外部服务返回404,我想避免再次调用这些任务,只是重试外部调用? I can't just wrap
future.get()
with a retryTemplate.execute()
because it won't actually make another call to the external service. 我不能只是包装
future.get()
与retryTemplate.execute()
因为它实际上并不会再拍调用外部服务。
You have to wrap the entire doSomething
(or at least the template operation and get) in a retry template. 您必须将整个
doSomething
(或至少模板操作和get)包装在重试模板中。
EDIT 编辑
Instead of calling get()
you could add a ListenableFutureCallback
to the future; 您可以在未来添加
ListenableFutureCallback
,而不是调用get()
; something like this... 像这样的东西......
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.