环境:
SpringBoot版本: 2.1.13.RELEASE
项目中遇到请求某个服务时需要带上特定的token和appKey, 但是请求其他服务不需要带. 所以需要使用到Feign局部配置功能.
代码如下:
/**
* 类FeignRequestInterceptor.java的实现描述:增加请求头,需要根据包配置
*
* @author dorra 2022/7/7 9:19:19
*/
//@Configuration 此处不能加@Configuration,加了就是全局配置
public class FeignRequestInterceptor implements RequestInterceptor {
private static final String datahouse_auth_name = "appKey";
private static final String default_appKey = "XXX";
@Value("${feignRequest.appKey}")
private String appKey;
/*
* 设置请求头
*
* @see feign.RequestInterceptor#apply(feign.RequestTemplate)
*/
@Override
public void apply(RequestTemplate template) {
if (StringUtils.isBlank(appKey)) {
appKey = default_appKey;
}
template.header(datahouse_auth_name, appKey);
}
}
注意: 不能加@Configuration,加了就是全局配置
/**
* 增加请求头,需要根据包配置,需要请在@FeignClient加上属性: configuration = FeignRequestConfig.class
* @author dorra
* @date 2022/8/10 11:12
*/
//此处不能加@Configuration,加了就是全局配置
public class FeignRequestConfig {
@Bean
public FeignRequestInterceptor feignRequestInterceptor() {
return new FeignRequestInterceptor();
}
}
注意: 不能加@Configuration,加了就是全局配置
使用:
@FeignClient(name = "data-server", url = "${dataserver}", configuration = FeignRequestConfig.class)
public interface DataServer {
}
参考文章: