guava-retrying重试练习

package com.example.demo.guava;
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.google.common.base.Predicates;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

public class GuavaRetry {
    private static final Logger log = LoggerFactory.getLogger(GuavaRetry.class);
    static Retryer retryer;

    static int count = 0;

    static {
        retryer = RetryerBuilder.newBuilder().retryIfResult(Predicates.equalTo("")) // 返回false时重试
                .withWaitStrategy(WaitStrategies.fixedWait(1000, TimeUnit.MILLISECONDS)) // 1000ms后重试
                .withStopStrategy(StopStrategies.stopAfterAttempt(3)) // 重试3次后停止
                .build();
    }

    public static void main(String[] args) throws InterruptedException {
        getWebPageSource();
    }

    public static String getWebPageSource() {

        try {
            return retryer.call(new Callable() {
                @Override
                public String call() throws Exception {
                    //
                    count++;
                    //
                    String res = "";
                    try {
                        URL url = new URL("https://yq.aliyun.com/articles/609440");// 根据链接(字符串格式),生成一个URL对象
                        String encoding = new String("UTF-8");
                        HttpURLConnection urlConnection = (HttpURLConnection) url
                                .openConnection();// 打开URL

                        BufferedReader reader = new BufferedReader(new InputStreamReader(
                                urlConnection.getInputStream(), encoding));// 得到输入流,即获得了网页的内容
                        String line; // 读取输入流的数据,并显示
                        while ((line = reader.readLine()) != null) {
                            System.out.println(line);
                        }
                    } catch (Exception e) {
                        log.debug(e.getMessage());
                    }
                    log.debug(count + "--" + String.valueOf(res.length()));
                    //
                    return res;
                }
            });
        } catch (Exception e) {
            return "";
        }
    }
}

你可能感兴趣的:(guava)