springboot 2.0对应springcloud Finchley Feign内部调用微服务时带上请求头(header)信息

场景:A模块,要通过feign调另外一个模块B的接口,同时要把请求A模块的请求头参数header 传给B

模块B:  controller中的一个方法
    @Override
    @PostMapping("/list/{page}/{size}")
    public QueryResponseResult findList(@PathVariable("page") int page,@PathVariable("size") int size,@RequestBody QueryLostRequest queryLostRequest) {
        //获取头信息
        String authorization = request.getHeader("Authorization");
        System.out.println("authorization = " + authorization);
        return lostService.filterList(page - 1, size, queryLostRequest);
    }
模块A:Bclient
@FeignClient(value = "B",configuration = FeignConfig.class)
public interface Blient {

    @PostMapping("/lost/list/{page}/{size}")
    public QueryResponseResult findList(@PathVariable("page") int page, @PathVariable("size") int size, @RequestBody QueryLostRequest queryLostRequest);
}
模块A: 	自己写一个FeignConfig类,实现RequestInterceptor接口
@Configuration
public class FeignConfig 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());
        }
    }
}
模块A:  application.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

大功告成。
总结:
1.需要在配置文件写相应的配置信息
2.自己写一个feignconfig
3.在@FeignClient上加,configuration = FeignConfig.class

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值