当前位置 : 主页 > 编程语言 > java >

Guava Retryer(重试组件)

来源:互联网 收集:自由互联 发布时间:2023-12-16
pom.xml dependency groupIdcom.google.guava/groupId artifactIdguava/artifactId versionRELEASE/version scopecompile/scope /dependency dependency groupIdcom.github.rholder/groupId artifactIdguava-retrying/artifactId version2.0.0/version !-- 排除

pom.xml

<dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.github.rholder</groupId>
            <artifactId>guava-retrying</artifactId>
            <version>2.0.0</version>
            <!-- 排除与guava重复的依赖 -->
            <exclusions>
                <exclusion>
                    <groupId>com.google.guava</groupId>
                    <artifactId>guava</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.google.code.findbugs</groupId>
                    <artifactId>jsr305</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

code

public static void main(String[] args) {
        String msg = "aaabbb";
        Callable<Integer> task = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println("length:".concat(msg.length() + ""));
                return msg.length();
            }
        };
        //返回异常或返回6或返回null,都会触发重试机制。最多执行4次(首次 + 重试3次),每次延迟5s。
        Retryer<Integer> retryer = RetryerBuilder.<Integer>newBuilder()
                .retryIfResult(Predicates.<Integer>isNull())
                .retryIfResult(Predicates.equalTo(6))
                .retryIfExceptionOfType(Exception.class)
                .withStopStrategy(StopStrategies.stopAfterAttempt(4))
                .withWaitStrategy(WaitStrategies.fixedWait(5*1000, TimeUnit.MILLISECONDS))
                .build();
        try {
            retryer.call(task);
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (RetryException e) {
            log.error("重试3次依旧未能获得期望值");
//            e.printStackTrace();
        }
    }


【感谢龙石为本站提供数据共享交换平台 http://www.longshidata.com/pages/exchange.html】
上一篇:javastream流计算bigdecimal
下一篇:没有了
网友评论