方式一:配置容器类
@Slf4j
@Configuration
public class FeignConfig {
@Bean
public RequestInterceptor requestInterceptor(){
return requestTemplate -> {
requestTemplate.header("Content-Type","application/json;charset=UTF-8");
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes!=null){
Object session_user = requestAttributes.getAttribute("session_user",0);
if (session_user!=null){
try {
requestTemplate.header("session_user", URLEncoder.encode(JSON.toJSONString(session_user),"utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
Object session_member = requestAttributes.getAttribute("session_member",0);
if (session_member!=null) {
try {
requestTemplate.header("session_member", URLEncoder.encode(JSON.toJSONString(session_user), "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
};
}
}
方式二:继承请求拦截器
@Configuration
public class FeignConfig implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
//添加token
requestTemplate.header("Authorization", request.getHeader("Authorization"));
}
}
}