源代码
1、引入openfeign pom依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2、添加配置对象
package xxx;
import com.alibaba.fastjson.JSON;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import feign.Feign;
import feign.RequestInterceptor;
import feign.Target;
import feign.hystrix.SetterFactory;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.FeignClientProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Enumeration;
public class FeignConfig extends FeignClientProperties.FeignClientConfiguration {
private static final Logger logger = LoggerFactory.getLogger(FeignConfig.class);
/**
* 配置动态地址
* 请求头参数透传
* @return
*/
@Bean
public RequestInterceptor requestInterceptor() {
return requestTemplate -> {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//替换路径中变量xxx为具体值
String yunId = request.getHeader("xxx");
requestTemplate.uri(requestTemplate.request().url().replace("//","/"+yunId+"/"));
//透传请求header参数
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
String values = request.getHeader(name);
requestTemplate.header(name, values);
}
}
};
}
/**
* hystrix 相关配置,feign默认集成
* @return
*/
@Bean
public SetterFactory setterFactory(){
SetterFactory setterFactory =new SetterFactory() {
@Override
public HystrixCommand.Setter create(Target<?> target, Method method) {
String groupKey = target.name();
String commandKey = Feign.configKey(target.type(), method);
HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter()
// //设置统计指标60秒为一个时间窗口
// .withMetricsRollingStatisticalWindowInMilliseconds(1000 * 60)
// //超过80%失败率
// .withCircuitBreakerErrorThresholdPercentage(80)
// //操作5个开启短路器
// .withCircuitBreakerRequestVolumeThreshold(5)
//设置断路器的开启时间为60秒
// .withCircuitBreakerSleepWindowInMilliseconds(1000 * 60)
//设置信号量隔离
.withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE);
return HystrixCommand.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey))
.andCommandKey(HystrixCommandKey.Factory.asKey(commandKey))
.andCommandPropertiesDefaults(setter);
}
};
return setterFactory;
}
}