方式一:配置容器类

  1. @Slf4j
  2. @Configuration
  3. public class FeignConfig {
  4. @Bean
  5. public RequestInterceptor requestInterceptor(){
  6. return requestTemplate -> {
  7. requestTemplate.header("Content-Type","application/json;charset=UTF-8");
  8. RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
  9. if (requestAttributes!=null){
  10. Object session_user = requestAttributes.getAttribute("session_user",0);
  11. if (session_user!=null){
  12. try {
  13. requestTemplate.header("session_user", URLEncoder.encode(JSON.toJSONString(session_user),"utf-8"));
  14. } catch (UnsupportedEncodingException e) {
  15. e.printStackTrace();
  16. }
  17. }
  18. Object session_member = requestAttributes.getAttribute("session_member",0);
  19. if (session_member!=null) {
  20. try {
  21. requestTemplate.header("session_member", URLEncoder.encode(JSON.toJSONString(session_user), "utf-8"));
  22. } catch (UnsupportedEncodingException e) {
  23. e.printStackTrace();
  24. }
  25. }
  26. }
  27. };
  28. }
  29. }

方式二:继承请求拦截器

  1. @Configuration
  2. public class FeignConfig implements RequestInterceptor {
  3. @Override
  4. public void apply(RequestTemplate requestTemplate) {
  5. ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  6. if (attributes != null) {
  7. HttpServletRequest request = attributes.getRequest();
  8. //添加token
  9. requestTemplate.header("Authorization", request.getHeader("Authorization"));
  10. }
  11. }
  12. }