zoukankan      html  css  js  c++  java
  • 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();
            }
        }
    
    }
  • 相关阅读:
    cocos2d-x 3.0rc1 编译cpp-testsproject
    [wxWidgets]_[0基础]_[不常见但有用的类wxStandardPaths]
    教你摆脱低级程序猿 项目中cocopads的安装使用
    Android使用代码模拟HOME键的功能
    UVA 1508
    asp.net mvc5 安装
    Java_并发线程_Semaphore、CountDownLatch、CyclicBarrier、Exchanger
    crm操作产品实体
    BZOJ 3172 [Tjoi2013]单词 AC自己主动机(fail树)
    ADO与ADO.Net
  • 原文地址:https://www.cnblogs.com/ooo0/p/15014099.html
Copyright © 2011-2022 走看看