问题描述
在微服务的调用中,如果消费者通过feign调用生产者,然后生产者方法中需要用到请求头,从请求头中获得token,但是feign默认是不携带请求头的,因此即使消费者请求feign的时候请求头中携带了token,也没有传到生产者,就会报相关的错误。
解决方案
1.如果token直接在请求头中
解决方案:加一个拦截器
package com.tianju.rabbit.feign.interceptor;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
@Configuration
@Slf4j
public class FeignInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
// 获取 HttpServletRequest
ServletRequestAttributes attributes = (ServletRequestAttributes)
RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String token = request.getHeader("token");
if (null!=token && !"".equals(token)){
log.info(">>> feign拦截器获取token:{}",token);
requestTemplate.header("token", token);
}
}
}
2.如果token在cookie里面
代码需要稍微做些修改
package com.tianju.rabbit.feign.interceptor;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
@Configuration
@Slf4j
public class FeignInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
// 获取 HttpServletRequest
ServletRequestAttributes attributes = (ServletRequestAttributes)
RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
Cookie[] cookies = request.getCookies();
for(Cookie cookie:cookies){
if ("token".equals(cookie.getName())){
// 把TOKEN带到下服务(token消息加到头消息)
log.debug(">>>> feign的拦截器,获取token:"+cookie.getValue());
requestTemplate.header("token",cookie.getValue());
}
}
}
}
总结
给feign加一个拦截器,设置一下请求头。