Java開發利器之重試框架guava-retrying

<dependency>      <groupId>com.github.rholder</groupId>      <artifactId>guava-retrying</artifactId>      <version>2.0.0</version></dependency>
package com.hhwy.demo.test;

import com.github.rholder.retry.Retryer;
import com.github.rholder.retry.RetryerBuilder;
import com.github.rholder.retry.StopStrategies;

public class Test {
    private int invokeCount = 0;

    @org.junit.Test
    public void guavaRetryTest() {
        Retryer<Integer> retryer = RetryerBuilder.<Integer>newBuilder()
                // 非正數進行重試
                .retryIfRuntimeException()
                // 偶數則進行重試
                .retryIfResult(result -> result % 2 == 0)
                // 設置最大執行次數3                .withStopStrategy(StopStrategies.stopAfterAttempt(3)).build();

        try {
            invokeCount=0;
            retryer.call(() -> realAction(0));
        } catch (Exception e) {
            System.out.println("執行0,異常:" + e.getMessage());
        }

        try {
            invokeCount=0;
            retryer.call(() -> realAction(1));
        } catch (Exception e) {
            System.out.println("執行1,異常:" + e.getMessage());
        }

        try {
            invokeCount=0;
            retryer.call(() -> realAction(2));
        } catch (Exception e) {
            System.out.println("執行2,異常:" + e.getMessage());
        }
    }


    public int realAction(int num) {
        invokeCount++;
        System.out.println(String.format("當前執行第 %d ,num:%d", invokeCount, num));
        if (num <= 0) {
            throw new IllegalArgumentException();
        }
        return num;
    }

}

https://mp.weixin.qq.com/s?__biz=Mzg2MjY2MjA1NA==&mid=2247484144&idx=1&sn=1aecfe9d4a05e27e78cca19056f2226e&chksm=ce053e39f972b72f042f17c3028a30e2887b52628839c20d3042e7a3408601aad14464ae0f76&mpshare=1&scene=23&srcid=1106tEXGcZijHXrqIdEsEMWC&sharer_sharetime=1636210510742&sharer_shareid=d784e408a595245164e5ac23bb41bc02#rd

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章