dog*_*ane 16
您可以RetriableTasks按照本文中的概述使用:在Java中重试操作.如果您愿意,可以很容易地更改其等待算法.
示例代码:
//creates a task which will retry 3 times with an interval of 5 seconds
RetriableTask r = new RetriableTask(3, 5000, new Callable(){
public Object call() throws Exception{
//put your code here
}
});
r.call();
Run Code Online (Sandbox Code Playgroud)
Jon*_*han 14
查看故障保险.它是一个简单的零依赖库,用于执行重试,支持同步和异步重试,Java 8集成,事件监听器,与其他异步API的集成等:
RetryPolicy retryPolicy = new RetryPolicy()
.handle(ConnectException.class, SocketException.class);
.withMaxRetries(3);
Connection connection = Failsafe.with(retryPolicy).get(() -> connect());
Run Code Online (Sandbox Code Playgroud)
不容易.
如果你使用Spring:
//import the necessary classes
import org.springframework.batch.retry.RetryCallback;
import org.springframework.batch.retry.RetryContext;
import org.springframework.batch.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.batch.retry.policy.SimpleRetryPolicy;
import org.springframework.batch.retry.support.RetryTemplate;
...
// create the retry template
final RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(new SimpleRetryPolicy(5));
final ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
backOffPolicy.setInitialInterval(1000L);
template.setBackOffPolicy(backOffPolicy);
// execute the operation using the retry template
template.execute(new RetryCallback<Remote>() {
@Override
public Remote doWithRetry(final RetryContext context) throws Exception {
return (Remote) Naming.lookup("rmi://somehost:2106/MyApp");
}
});
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Spring,那么使用Spring Retry Library 非常简单。
现在,Spring Retry是一个单独的库(之前是Spring Batch的一部分)框架。
步骤1:添加spring retry依赖项。
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.1.2.RELEASE</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
步骤2:@EnableRetry在您的类中添加注释,该注释包含应用程序的main()方法或任何类中的注释@Configuration。
步骤3:@Retryable在您的方法中添加注释,以防万一,请重试/调用。
@Retryable(maxAttempts=5,backoff = @Backoff(delay = 3000))
public void retrySomething() throws Exception{
logger.info("printSomething{} is called");
throw new SQLException();
}
Run Code Online (Sandbox Code Playgroud)
此@Retryable注释将重试/调用retrySomething()5次(包括第一次失败)。
当前线程将在下一次重试之间等待3000毫秒或3秒。
| 归档时间: |
|
| 查看次数: |
20776 次 |
| 最近记录: |