1、问题描述
我们在SpringCloud中使用Feign请求另一个服务的Api接口时,有将Header中参数传递下去的需求,如果不做特殊处理,就会将Header中的参数丢失。
2、解决方案
通过实现 RequestInterceptor 接口
(1)、首先,自定义实现RequestInterceptor接口的apply方法,如下
package com.shareworx.auth.security.feign;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
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.util.Enumeration;
public class CommonFeignConfiguration implements RequestInterceptor {
@Override
public void apply(RequestTemplate template) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
String values = request.getHeader(name);
if (StringUtils.isNotBlank(values) && "authorization".equals(name.toLowerCase())) {
template.header(name, values);
}
}
}
}
}
/**
* 配置Feign日志级别
* @return
*/
@Bean
Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
@Bean
public Encoder feignFormEncoder() {
return new SpringFormEncoder(new SpringEncoder(messageConverters));
}
}
我这边在项目上遇到的只需要传递"authorization"参数,因此多加了一个条件判断
if(StringUtils.isNotBlank(values)&&"authorization".equals(name.toLowerCase())){
template.header(name,values);
}
(2)、然后将自定义的配置类配置到Feign中,就可以实现该Feign中接口Header参数的传递
package com.shareworx.auth.security.feign;
import com.shareworx.auth.security.fallback.SecurityBaseUserFeignServiceFallbackFactory;
import com.shareworx.auth.shiro.model.BaseProjectVO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@FeignClient(contextId = "SecurityHoProjectInitFeignService", name = "xx-server",configuration = CommonFeignConfiguration.class)
public interface SecurityHoProjectInitFeignService {
}