超时设置
feign:
okhttp:
enabled: true
client:
config:
default:
loggerLevel: basic
readTimeout: 20000
connectTimeout: 5000
开启Feign重试
package com.cspg.snlsct.cs.config;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class RetryIntercepter implements Interceptor {
public int maxRetry;
private int retryNum = 0;
public RetryIntercepter(int maxRetry) {
this.maxRetry = maxRetry;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
while (!response.isSuccessful() && retryNum < maxRetry) {
retryNum++;
response = chain.proceed(request);
}
return response;
}
}
添加在Feign的配置类
package com.cspg.snlsct.cs.config;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;
@Configuration
public class FeignOkHttpConfig {
@Bean
public ConnectionPool pool() {
return new ConnectionPool(200, 30, TimeUnit.MINUTES);
}
@Bean
public OkHttpClient okHttpClient() {
return new OkHttpClient.Builder()
.retryOnConnectionFailure(true)
.connectionPool(pool())
.connectTimeout(20L, TimeUnit.SECONDS)
.readTimeout(20L, TimeUnit.SECONDS)
.followRedirects(true)
.addInterceptor(new RetryIntercepter(5))
.build();
}
}
Feign全局加自定义请求头(其他)
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "datam")
public class DatamConfig {
private static final long serialVersionUID = 1L;
@ApiModelProperty("地址")
private String url;
@ApiModelProperty("API-KEY")
private String apikey;
}
import cn.hutool.extra.spring.SpringUtil;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignRequestInterceptor implements RequestInterceptor {
private DatamConfig datamConfig;
@ApiModelProperty("API-KEY")
@Getter
public static String apiKey;
@Bean
Logger.Level photovoltFeignLevel(){
return Logger.Level.FULL;
}
@Override
public void apply(RequestTemplate requestTemplate) {
this.datamConfig = SpringUtil.getBean(DatamConfig.class);
this.apiKey = datamConfig.getApikey();
requestTemplate.header("API-KEY", apiKey);
}
}