Feign调用请求头中添加公共请求参数

总监:小王啊,最近项目feign调用需要传递一个公共参数,而且这里我还想在feign调用的请求头里面添加当前接口被请求时所携带的所有请求头。

我:在调用的时候加头参数呗。

总监:那不行呀,太麻烦了,我需要一个一劳永逸的方法。

我:好吧…我看看怎么弄吧。


思路:

  1. 在用feign发送请求之前,遍历当前请求头里面的所有信息,加到要请求的地址的头里面。
  2. 单独添加一个参数在所有feign请求头之中。

代码实现如下:

@Configuration
public class FeignConfiguration implements feign.RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        //开启多线程调用的时候,线程并没有request,防止这里报空指针
        if(attributes==null){
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                // 跳过 content-length
                if (name.equals("content-length")){
                    continue;
                }
                requestTemplate.header(name, values);
            }
        }
        //这里最后向requestTemplate里面放入一个是否为feign调用的标记
        requestTemplate.header("isFeign","true");
    }

}

好啦!搞定!👍👍👍👍👍👍
在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值