1.配置拦截器
import java.io.IOException;
import java.io.InterruptedIOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpRetryInterceptor implements Interceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(OkHttpRetryInterceptor.class);
/**
* 最大重试次数
*/
private int executionCount;
/**
* 重试的间隔
*/
private long retryInterval;
OkHttpRetryInterceptor(Builder builder) {
this.executionCount = builder.executionCount;
this.retryInterval = builder.retryInterval;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = doRequest(chain, request);
int retryNum = 0;
while ((response == null || !response.isSuccessful()) && retryNum <= executionCount) {
LOGGER.info("intercept Request is not successful - {}", retryNum);
final long nextInterval = getRetryInterval();
try {
LOGGER.info("Wait for {}", nextInterval);
Thread.sleep(nextInterval);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
throw new InterruptedIOException();
}
retryNum++;
// retry the request
response = doRequest(chain, request);
}
return response;
}
private Response doRequest(Chain chain, Request request) {
Response response = null;
try {
response = chain.proceed(request);
} catch (Exception e) {
}
return response;
}
/**
* retry间隔时间
*/
public long getRetryInterval() {
return this.retryInterval;
}
public static final class Builder {
private int executionCount;
private long retryInterval;
public Builder() {
executionCount = 3;
retryInterval = 1000;
}
public Builder executionCount(int executionCount) {
this.executionCount = executionCount;
return this;
}
public Builder retryInterval(long retryInterval) {
this.retryInterval = retryInterval;
return this;
}
public OkHttpRetryInterceptor build() {
return new OkHttpRetryInterceptor(this);
}
}
}
2.注入feignClient bean
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.netflix.feign.FeignAutoConfiguration;
import org.springframework.cloud.netflix.feign.ribbon.CachingSpringLoadBalancerFactory;
import org.springframework.cloud.netflix.feign.ribbon.LoadBalancerFeignClient;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import feign.Client;
import feign.Feign;
import feign.ribbon.RibbonClient;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
@Configuration
@ConditionalOnMissingBean({ OkHttpClient.class, Client.class })
@ConditionalOnClass(Feign.class)
@AutoConfigureBefore(FeignAutoConfiguration.class)
public class FeignClientConfig {
@Value("${feign.invoke.http.connectTimeoutMillis:3000}")
private int connectTimeoutMillis;
@Value("${feign.invoke.http.readTimeoutMillis:10000}")
private int readTimeoutMillis;
@Value("${feign.invoke.http.retryExecutionCount:3}")
private int retryExecutionCount;
@Value("${feign.invoke.http.retryInterval:1000}")
private int retryInterval;
public FeignClientConfig() {
}
@Bean
@ConditionalOnMissingBean({ OkHttpClient.class })
public OkHttpClient okHttpClient() {
OkHttpRetryInterceptor okHttpRetryInterceptor = new OkHttpRetryInterceptor.Builder().executionCount(retryExecutionCount)
.retryInterval(retryInterval)
.build();
return new OkHttpClient.Builder().retryOnConnectionFailure(true)
.addInterceptor(okHttpRetryInterceptor)
.connectionPool(new ConnectionPool())
.connectTimeout(connectTimeoutMillis, TimeUnit.MILLISECONDS)
.readTimeout(readTimeoutMillis, TimeUnit.MILLISECONDS)
.build();
}
@Bean
@ConditionalOnMissingBean({ Client.class })
public Client feignClient(CachingSpringLoadBalancerFactory cachingFactory, SpringClientFactory clientFactory) {
if (cachingFactory == null) {
RibbonClient.Builder builder = RibbonClient.builder();
builder.delegate(new feign.okhttp.OkHttpClient(this.okHttpClient()));
return builder.build();
} else {
return new LoadBalancerFeignClient(new feign.okhttp.OkHttpClient(this.okHttpClient()), cachingFactory,
clientFactory);
}
}
}
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-ribbon</artifactId>
<version>9.0.0</version>
</dependency>
4.写feignClient
@FeignClient(name = "xxxApi", url = "${xxx.url}")
public interface xxxClient {
@RequestMapping(method = RequestMethod.POST)
public String createLink(@RequestHeader(name = "accessKey", defaultValue = "xx") String accessKey,
@RequestHeader(name = "accessSecret") String accessSecret, @RequestBody String linkConfig);
}
5.写熔断器
@Autowired
private xxxClient xxClient;
@HystrixCommand(commandKey = "xxxLink", fallbackMethod = "xxxError", commandProperties = { @HystrixProperty(name = "requestCache.enabled", value = "true"),
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000") })
public String xxLink(String accessKey, String accessSecret, String linkConfig) {
LOG.info("[xxLink] LinkConfig is {}", linkConfig);
String resp = xxxClient.createLink(accessKey, accessSecret, linkConfig);
LOG.info("[xxxLink] response : {}", resp);
return resp;
}
参考博文:
http://okeeper.leanote.com/post/%E4%BD%BF%E7%94%A8Spring-Cloud-Feign%E4%BD%9C%E4%B8%BAHTTP%E5%AE%A2%E6%88%B7%E7%AB%AF%E8%B0%83%E7%94%A8%E8%BF%9C%E7%A8%8BHTTP%E6%9C%8D%E5%8A%A1
https://segmentfault.com/a/1190000009071952 Alan的回答