All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.feingto.cloud.kit.http.OKHttpRetryIntercepter Maven / Gradle / Ivy

There is a newer version: 2.5.2.RELEASE
Show newest version
package com.feingto.cloud.kit.http;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.io.InterruptedIOException;

/**
 * OKHttp 响应失败重试
 *
 * @author longfei
 */
@Slf4j
public class OKHttpRetryIntercepter implements Interceptor {
    /**
     * 最大重试次数
     */
    private final int maxAutoRetries;

    /**
     * 重试频率
     */
    private final int retryInterval;

    public OKHttpRetryIntercepter(int maxAutoRetries, int retryInterval) {
        this.maxAutoRetries = maxAutoRetries;
        this.retryInterval = retryInterval;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        int retryNum = 0;
        while (!response.isSuccessful() && retryNum < maxAutoRetries) {
            try {
                Thread.sleep(retryInterval);
            } catch (final InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new InterruptedIOException();
            }
            retryNum++;
            log.error("Request failed and retried {} times", retryNum);
            response = chain.proceed(request);
        }
        return response;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy