com.github.rbuck.retry.SqlRetryPolicy Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-retry Show documentation
Show all versions of java-retry Show documentation
Lets developers make their applications more resilient by adding robust
transient fault handling logic. Transient faults are errors that occur
because of some temporary condition such as network connectivity issues
or service unavailability. Typically, if you retry the operation that
resulted in a transient error a short time later, you find that the
error has disappeared.
package com.github.rbuck.retry;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.Callable;
/**
* A retry policy for SQL operations.
*
* @author Robert Buck ([email protected])
*/
public class SqlRetryPolicy {
private final SqlTransactionContext sqlTransactionContext;
private final RetryPolicy retryPolicy;
/**
* Implements a retry policy using the specified strategy and transient error detection algorithm.
*
* @param retryStrategy the strategy that implements retry
*/
public SqlRetryPolicy(RetryStrategy retryStrategy, SqlTransactionContext sqlTransactionContext) {
this(retryStrategy, new SqlTransientExceptionDetector(), sqlTransactionContext);
}
/**
* Implements a retry policy using the specified strategy and transient error detection algorithm.
*
* @param retryStrategy the strategy that implements retry
* @param transientExceptionDetector the transient error detection algorithm
*/
public SqlRetryPolicy(RetryStrategy retryStrategy, TransientExceptionDetector transientExceptionDetector, SqlTransactionContext sqlTransactionContext) {
this.retryPolicy = new RetryPolicy<>(retryStrategy, transientExceptionDetector);
this.sqlTransactionContext = sqlTransactionContext;
}
public V action(final SqlCallable callable) throws Exception {
return retryPolicy.action(new Callable() {
@Override
public V call() throws Exception {
try (Connection connection = sqlTransactionContext.getConnection()) {
try {
V value = callable.call(connection);
connection.commit();
return value;
} catch (SQLException se) {
if (!SqlTransientExceptionDetector.isSqlStateConnectionException(se)) {
try {
connection.rollback();
} catch (SQLException ignored) {
}
}
throw se;
}
}
}
});
}
}