Spring-retry and guava Retry both provide retry tools, but both have one disadvantage, that is, if the retry wait process will block the worker threads, which is risky for use in production environments. If there are a large number of long-term retry tasks, it will consume system thread resources. The following is based on the thread pool to complete a simple retry tool class.
Core idea
Encapsulate the task as a task, put the task's retry into a scheduleable thread pool to complete execution, avoiding the threads falling into meaningless waiting during the retry interval, and abstracting the retry mechanism into a retry strategy.
Code implementation
Retry the tool class
package .v2; import .slf4j.Slf4j; import ; import ; import ; import ; import ; import ; @Slf4j public class RetryUtil { public static ExecutorService EXECUTOR = (1); private static final ScheduledExecutorService SCHEDULER_EXECUTOR = (20); /** * Task retry * @param actualTaskFunction Execution task function * @param resultHandler Task result handler * @param maxRetry Maximum number of retries * @param retryStrategy Retry the strategy */ public static void retryTask( Function<Integer, String> actualTaskFunction, Function<String, Boolean> resultHandler, int maxRetry, RetryStrategy retryStrategy //Use policy mode ) { Runnable runnable = new Runnable() { final AtomicInteger retryCount = new AtomicInteger(); // Current number of retry final AtomicInteger maxRetryCount = new AtomicInteger(maxRetry); // Maximum number of retry @Override public void run() { String taskResult = (()); // Execute tasks Boolean taskSuccess = (taskResult); // Process the task results if (taskSuccess) { if (() > 1) { ("Task retry successfully,Number of retry times:{}", ()); } return; // The task is successful, no need to try again } if (() == ()) { ("Task retry failed,Number of retry times:{}", ()); return; // Retry the maximum number of retry times is reached. } // Get the retry interval long delay = (()); TimeUnit timeUnit = (()); // Schedule a try again next time SCHEDULER_EXECUTOR.schedule(this, delay, timeUnit); ("Task retry failed,wait {} {} Try again afterward,当前Number of retry times:{}", delay, timeUnit, ()); } }; (runnable); // Execute tasks } public static void main(String[] args) { // Use exponential backoff retry strategy RetryStrategy retryStrategy = new ExponentialBackoffRetryStrategy(1, ); retryTask( retryCount -> "task result", taskResult -> () < 0.1, 5, retryStrategy ); } }
Retry the policy
Exponential backoff
package .v2; import ; /** * Exponential backoff retry strategy */ public class ExponentialBackoffRetryStrategy implements RetryStrategy { private final long initialDelay; private final TimeUnit timeUnit; public ExponentialBackoffRetryStrategy(long initialDelay, TimeUnit timeUnit) { = initialDelay; = timeUnit; } @Override public long getDelay(int retryCount) { return (long) (initialDelay * (2, retryCount - 1)); // Exponential backoff } @Override public TimeUnit getTimeUnit(int retryCount) { return timeUnit; } }
Custom retry interval time
package .v2; import ; import ; /** * Custom retry policy for retry interval time */ public class CustomerIntervalRetryStrategy implements RetryStrategy { // Configure retry interval and time units List<RetryInterval> retryIntervals; public CustomerIntervalRetryStrategy(List<RetryInterval> retryIntervals) { = retryIntervals; } @Override public long getDelay(int retryCount) { return (retryCount).getDelay(); } @Override public TimeUnit getTimeUnit(int retryCount){ return (retryCount).getTimeUnit(); } }
Fixed interval
package .v2; import ; /** * Fixed interval retry strategy */ public class FixedIntervalRetryStrategy implements RetryStrategy { private final long interval; private final TimeUnit timeUnit; public FixedIntervalRetryStrategy(long interval, TimeUnit timeUnit) { = interval; = timeUnit; } @Override public long getDelay(int retryCount) { return interval; } @Override public TimeUnit getTimeUnit(int retryCount) { return timeUnit; } }
This is the end of this article about Java implementation of custom retry tool classes. For more related contents of Java retry tool classes, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!