feat:限流+重试+
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
package com.xiang.xservice.http.config;
|
||||
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
@ConfigurationProperties(prefix = "http")
|
||||
public class HttpConfig {
|
||||
|
||||
/**
|
||||
* 最大重试次数
|
||||
*/
|
||||
private int maxAttempts;
|
||||
|
||||
/**
|
||||
* 重试等待时间 ms
|
||||
*/
|
||||
private long sleepMs;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.xiang.xservice.http.helper;
|
||||
|
||||
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.xiang.xservice.http.config.HttpConfig;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class HttpRequestHelper {
|
||||
|
||||
private final HttpConfig httpConfig;
|
||||
|
||||
/**
|
||||
* 封装带重试和延迟的请求调用
|
||||
*
|
||||
* @param supplier 实际请求的逻辑
|
||||
* @param logTag 日志标识(便于排查)
|
||||
* @param <T> 返回值类型
|
||||
* @return 请求结果,如果失败则返回 null
|
||||
*/
|
||||
public <T> T fetchWithRetry(Supplier<T> supplier, String logTag) {
|
||||
Retryer<T> retryer = RetryerBuilder.<T>newBuilder()
|
||||
.retryIfException()
|
||||
.retryIfResult(Objects::isNull)
|
||||
// 重试等待间隔
|
||||
.withWaitStrategy(WaitStrategies.fixedWait(httpConfig.getSleepMs(), TimeUnit.MILLISECONDS))
|
||||
// 最大重试次数
|
||||
.withStopStrategy(StopStrategies.stopAfterAttempt(httpConfig.getMaxAttempts()))
|
||||
.build();
|
||||
|
||||
Callable<T> callable = () -> {
|
||||
T result = supplier.get();
|
||||
// 每次请求后固定等待,用于限速
|
||||
Thread.sleep(httpConfig.getSleepMs());
|
||||
return result;
|
||||
};
|
||||
try {
|
||||
return retryer.call(callable);
|
||||
} catch (Exception e) {
|
||||
log.warn("[{}] 请求失败,重试 {} 次后仍未成功,错误: {}", logTag, httpConfig.getMaxAttempts(), e.getMessage(), e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
||||
com.xiang.xservice.http.config.HttpConfig
|
||||
Reference in New Issue
Block a user