提交 bcec8a69 编写于 作者: 如梦技术's avatar 如梦技术 🐛

mica-http 去掉 spring retry 依赖。

上级 971221b4
/*
* Copyright (c) 2019-2029, Dreamlu (596392912@qq.com & www.dreamlu.net).
* Copyright (c) 2019-2029, Dreamlu 卢春梦 (596392912@qq.com & www.dreamlu.net).
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
......@@ -14,45 +14,27 @@
* limitations under the License.
*/
package net.dreamlu.mica.http;
package net.dreamlu.mica.core.retry;
import lombok.Getter;
import lombok.ToString;
import org.springframework.retry.policy.SimpleRetryPolicy;
import javax.annotation.Nullable;
import java.util.function.Predicate;
import net.dreamlu.mica.core.function.CheckedCallable;
/**
* 重试策略
* 重试接口
*
* @author dream.lu
* @author L.cm
*/
@Getter
@ToString
public class RetryPolicy {
public static final RetryPolicy INSTANCE = new RetryPolicy();
private final int maxAttempts;
private final long sleepMillis;
@Nullable
private final Predicate<ResponseSpec> respPredicate;
public RetryPolicy() {
this(null);
}
public RetryPolicy(int maxAttempts, long sleepMillis) {
this(maxAttempts, sleepMillis, null);
}
public RetryPolicy(@Nullable Predicate<ResponseSpec> respPredicate) {
this(SimpleRetryPolicy.DEFAULT_MAX_ATTEMPTS, 0L, respPredicate);
}
public interface IRetry {
/**
* Execute the supplied {@link CheckedCallable} with the configured retry semantics. See
* implementations for configuration details.
*
* @param <T> the return value
* @param retryCallback the {@link CheckedCallable}
* @param <E> the exception thrown
* @return T the return value
* @throws E the exception thrown
*/
<T, E extends Throwable> T execute(RetryCallback<T, E> retryCallback) throws E;
public RetryPolicy(int maxAttempts, long sleepMillis, @Nullable Predicate<ResponseSpec> respPredicate) {
this.maxAttempts = maxAttempts;
this.sleepMillis = sleepMillis;
this.respPredicate = respPredicate;
}
}
package net.dreamlu.mica.core.retry;
import java.io.Serializable;
/**
* Callback interface for an operation that can be retried using a
*
* @param <T> the type of object returned by the callback
* @param <E> the type of exception it declares may be thrown
* @author Rob Harrop
* @author Dave Syer
*/
public interface RetryCallback<T, E extends Throwable> extends Serializable {
/**
* Execute an operation with retry semantics. Operations should generally be
* idempotent, but implementations may choose to implement compensation semantics when
* an operation is retried.
*
* @return the result of the successful operation.
* @throws E of type E if processing fails
*/
T call() throws E;
}
/*
* Copyright (c) 2019-2029, Dreamlu 卢春梦 (596392912@qq.com & www.dreamlu.net).
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.dreamlu.mica.core.retry;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.Exceptions;
import net.dreamlu.mica.core.utils.ThreadUtil;
import java.io.IOException;
/**
* 简单的 retry 重试
*
* @author L.cm
*/
@Slf4j
public final class SimpleRetry implements IRetry {
/**
* The default limit to the number of attempts for a new policy.
*/
public final static int DEFAULT_MAX_ATTEMPTS = 3;
/**
* Default back off period - 1ms.
*/
private static final long DEFAULT_BACK_OFF_PERIOD = 1L;
/**
* 重试次数
*/
private final int maxAttempts;
/**
* 重试时间间隔
*/
private final long sleepMillis;
public SimpleRetry() {
this(DEFAULT_MAX_ATTEMPTS, DEFAULT_BACK_OFF_PERIOD);
}
public SimpleRetry(int maxAttempts) {
this(maxAttempts, DEFAULT_BACK_OFF_PERIOD);
}
public SimpleRetry(int maxAttempts, long sleepMillis) {
this.maxAttempts = maxAttempts;
this.sleepMillis = (sleepMillis > 0 ? sleepMillis : 1);
}
public int getMaxAttempts() {
return maxAttempts;
}
public long getSleepMillis() {
return sleepMillis;
}
@Override
public <T, E extends Throwable> T execute(RetryCallback<T, E> retryCallback) throws E {
int retryCount;
Throwable lastThrowable = null;
for (int i = 0; i < maxAttempts; i++) {
try {
return retryCallback.call();
} catch (Throwable e) {
retryCount = i + 1;
log.warn("retry on {} times.", retryCount, e);
lastThrowable = e;
if (sleepMillis > 0 && retryCount < maxAttempts) {
ThreadUtil.sleep(sleepMillis);
}
}
}
if (lastThrowable == null) {
lastThrowable = new IOException("retry on " + maxAttempts + " times,still fail.");
}
throw Exceptions.unchecked(lastThrowable);
}
}
......@@ -4,5 +4,4 @@ dependencies {
}
api "com.squareup.okhttp3:okhttp:${okhttpVersion}"
api "com.squareup.okhttp3:logging-interceptor:${okhttpVersion}"
implementation "org.springframework.retry:spring-retry"
}
......@@ -16,6 +16,8 @@
package net.dreamlu.mica.http;
import net.dreamlu.mica.core.retry.IRetry;
import net.dreamlu.mica.core.retry.SimpleRetry;
import net.dreamlu.mica.core.ssl.DisableValidationTrustManager;
import net.dreamlu.mica.core.ssl.TrustAllHostNames;
import net.dreamlu.mica.core.utils.Exceptions;
......@@ -28,7 +30,10 @@ import okhttp3.internal.http.HttpMethod;
import okhttp3.logging.HttpLoggingInterceptor;
import javax.annotation.Nullable;
import javax.net.ssl.*;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
......@@ -92,7 +97,9 @@ public class HttpRequest {
@Nullable
private Authenticator proxyAuthenticator;
@Nullable
private RetryPolicy retryPolicy;
private IRetry retry;
@Nullable
private Predicate<ResponseSpec> respPredicate;
@Nullable
private Boolean disableSslValidation;
@Nullable
......@@ -279,8 +286,8 @@ public class HttpRequest {
if (followSslRedirects != null) {
builder.followSslRedirects(followSslRedirects);
}
if (retryPolicy != null) {
builder.addInterceptor(new RetryInterceptor(retryPolicy));
if (retry != null) {
builder.addInterceptor(new RetryInterceptor(retry, respPredicate));
}
if (logger != null && logLevel != null && HttpLoggingInterceptor.Level.NONE != logLevel) {
builder.addInterceptor(getLoggingInterceptor(logger, logLevel));
......@@ -482,22 +489,29 @@ public class HttpRequest {
}
public HttpRequest retry() {
this.retryPolicy = RetryPolicy.INSTANCE;
return this;
return retry(new SimpleRetry());
}
public HttpRequest retryOn(Predicate<ResponseSpec> respPredicate) {
this.retryPolicy = new RetryPolicy(respPredicate);
return this;
return retry(new SimpleRetry(), respPredicate);
}
public HttpRequest retry(int maxAttempts, long sleepMillis) {
this.retryPolicy = new RetryPolicy(maxAttempts, sleepMillis);
return this;
return retry(new SimpleRetry(maxAttempts, sleepMillis));
}
public HttpRequest retry(int maxAttempts, long sleepMillis, Predicate<ResponseSpec> respPredicate) {
this.retryPolicy = new RetryPolicy(maxAttempts, sleepMillis);
return retry(new SimpleRetry(maxAttempts, sleepMillis), respPredicate);
}
public HttpRequest retry(IRetry retry) {
this.retry = retry;
return this;
}
public HttpRequest retry(IRetry retry, Predicate<ResponseSpec> respPredicate) {
this.retry = retry;
this.respPredicate = respPredicate;
return this;
}
......
......@@ -17,14 +17,13 @@
package net.dreamlu.mica.http;
import lombok.RequiredArgsConstructor;
import net.dreamlu.mica.core.retry.IRetry;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.springframework.retry.backoff.FixedBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.function.Predicate;
......@@ -35,16 +34,16 @@ import java.util.function.Predicate;
*/
@RequiredArgsConstructor
public class RetryInterceptor implements Interceptor {
private final RetryPolicy retryPolicy;
private final IRetry retry;
@Nullable
private final Predicate<ResponseSpec> respPredicate;
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RetryTemplate template = createRetryTemplate(retryPolicy);
return template.execute(context -> {
return retry.execute(() -> {
Response response = chain.proceed(request);
// 结果集校验
Predicate<ResponseSpec> respPredicate = retryPolicy.getRespPredicate();
if (respPredicate == null) {
return response;
}
......@@ -59,16 +58,4 @@ public class RetryInterceptor implements Interceptor {
});
}
private static RetryTemplate createRetryTemplate(RetryPolicy policy) {
RetryTemplate template = new RetryTemplate();
// 重试策略
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(policy.getMaxAttempts());
// 设置间隔策略
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setBackOffPeriod(policy.getSleepMillis());
template.setRetryPolicy(retryPolicy);
template.setBackOffPolicy(backOffPolicy);
return template;
}
}
......@@ -29,7 +29,7 @@ public class HttpRequestProxyTest {
// 代理都不可用
HttpRequest.get("https://www.baidu.com")
.useConsoleLog(LogLevel.BASIC)
// .retry()
.retry()
.proxySelector(new MicaProxySelector())
.execute()
.asString();
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册