Guava Retry

依赖:

<dependency>
    <groupId>com.github.rholder</groupId>
    <artifactId>guava-retrying</artifactId>
    <version>2.0.0</version>
</dependency>

 

示例:

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.remoting.RemoteAccessException;

@Slf4j
public class RetryDemoTask {


    /**
     * 重试方法
     * @return
     */
    public static boolean retryTask(String param)  {
        log.info("收到请求参数:{}",param);

        int i = RandomUtils.nextInt(0,11);
        log.info("随机生成的数:{}",i);
        if (i < 2) {
            log.info("<2,抛出参数异常.");
            throw new IllegalArgumentException("参数异常");
        }else if (i  < 5){
            log.info("<5,返回true.");
            return true;
        }else if (i < 7){
            log.info("<7,返回false.");
            return false;
        }else{
            //为其他
            log.info("else,抛出自定义异常.");
            throw new RemoteAccessException("else,抛出自定义异常");
        }
    }

}
import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.StopStrategies;
import com.github.rholder.retry.WaitStrategies;
import com.xc.xcspringboot.test.Retry.RetryDemoTask;
import org.junit.Test;
import org.springframework.remoting.RemoteAccessException;

import java.util.concurrent.TimeUnit;

public class GuavaRetryTest {


    @Test
    public void fun01() {
        // RetryerBuilder 构建重试实例 retryer,可以设置重试源且可以支持多个重试源,可以配置重试次数或重试超时时间,以及可以配置等待时间间隔
        Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
                .retryIfExceptionOfType(RemoteAccessException.class)//设置异常重试源
                .retryIfResult(res -> res != null && !res)  //设置根据结果重试
                .withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS)) //设置等待间隔时间
                .withStopStrategy(StopStrategies.stopAfterAttempt(3)) //设置最大重试次数
                .build();

        try {
            retryer.call(() -> RetryDemoTask.retryTask("abc"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

 

posted @ 2021-07-15 10:02  草木物语  阅读(450)  评论(0编辑  收藏  举报