SpringBoot 2 Feign内部调用时带上请求头(header)信息

本文介绍了解决Feign内部模块调用时Token信息丢失的问题,通过配置FeignConfiguration类,确保请求头信息在跨模块调用时能够完整传递,避免了因Token缺失导致的数据保存不全问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目中经常涉及内部模块之间的相互调用,导致在用A模块调用B模块的方法时,请求头里面的token信息传递不到B模块,从而获取不到用户信息,导致保存数据时,保存的数据不全,根据网上一些博客写此篇博客以作记录,代码中如有错漏之处,请各位大神海涵!
(下面的操作步骤没关系,只要有就可以)

1.Configuration代码

package com.xxx.demo;

import feign.RequestInterceptor;
import feign.RequestTemplate;
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;
import java.util.Enumeration;

/**
 * @description: Feign内部调用时带上请求头信息
 * @author: xxx
 * @create: 2019-08-09 10:02
 * 注意:要去yml里面改变hystrix Feign的隔离策为strategy: SEMAPHORE
 **/
@Configuration
public class FeignConfiguration implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                template.header(name, values);
            }
        }
        Enumeration<String> bodyNames = request.getParameterNames();
        StringBuffer body =new StringBuffer();
        if (bodyNames != null) {
            while (bodyNames.hasMoreElements()) {
                String name = bodyNames.nextElement();
                String values = request.getParameter(name);
                body.append(name).append("=").append(values).append("&");
            }
        }
        if(body.length()!=0) {
            body.deleteCharAt(body.length()-1);
            template.body(body.toString());
        }
    }
}

2.yml配置

feign:
  hystrix:
    enabled: true
  client:
    config:
      default:
        connectTimeout: 60000
        readTimeout: 60000

hystrix:
  command:
    default:
      execution:
        timeout:
          enabled: true
        isolation:
          strategy: SEMAPHORE
          thread:
            timeoutInMilliseconds: 60000

3.Feignclient调用的时候指定configuration

package com.xxx.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Map;

@FeignClient(name = "device", configuration = FeignConfiguration.class)
public interface MonitorNetService {

    @RequestMapping(value = "api/monitorNetImport", method = RequestMethod.POST)
    public Map<String, Object> monitorNetImport(@RequestBody Map<String, String> params);
}
### 解决方案 当从 Apache Tomcat 9.0.8 升级到 9.0.98 后遇到 Spring Boot 应用程序中 Feign 客户端无法获取请求头的情况,通常是因为某些默认行为或配置发生了变化。以下是解决方案: #### 修改 `feign.RequestInterceptor` 实现类 为了确保自定义的 HTTP 请求头能够被传递给远程服务,在应用程序中实现 `RequestInterceptor` 接口并重写其方法来添加必要的头部信息。 ```java import feign.RequestTemplate; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; @Component public class CustomFeignConfig { @Bean public RequestInterceptor requestInterceptor() { return new RequestInterceptor() { @Override public void apply(RequestTemplate template) { // 获取当前线程中的上下文数据(如通过ThreadLocal) String customHeader = "example-value"; // 替换成实际逻辑 // 添加自定义header template.header("Custom-Header", customHeader); // 如果需要转发原始请求的所有headers,则遍历HttpServletRequest对象并将它们复制过来 /* * HttpServletRequest originalRequest = ...; Enumeration<String> headerNames = * originalRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = * headerNames.nextElement(); String value = originalRequest.getHeader(name); template.header(name, * value); } */ } }; } } ``` #### 更新依赖版本 确认项目的构建工具(Maven 或 Gradle)配置文件中使用的 spring-cloud-openfeign 和其他相关库是最新的稳定版,因为旧版本可能存在兼容性问题[^1]。 对于 Maven 用户来说,应该更新 pom.xml 文件内的依赖项如下所示: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>${latest.version}</version> </dependency> ``` 替换 `${latest.version}` 为最新发布的版本号。 #### 检查服务器配置差异 对比新老版本之间的 server.properties 设置是否有变动影响到了HTTP协议栈的行为方式;另外还要注意查看是否存在安全策略上的调整阻止了特定类型的元数据传输[^2]。 如果以上措施仍未能解决问题,建议深入研究官方文档以及社区论坛寻找更多线索或者提交issue寻求帮助。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值