Spring Cloud Feign传输Header,并保证多线程情况下也适用

Spring Cloud Feign传输Header,并保证多线程情况下也适用

一、现象

微服务在生产中,常遇到需要把 header 传递到下一子服务的情况(如服务A访问服务B的接口,需要传递header),网上大多数的方案是实现 RequestInterceptor 接口,在重写方法中,把 header 填进 Feign 的请求中。我们先按这种方式,简单实现代码如下:

1、继承RequestInterceptor

服务A新建类,继承 RequestInterceptor,把 header 设置到请求中,注意 header 的key若是大写时,请求中一般会被转为小写,所以建议header的key一般设置为小写。

package com.he.feign.config;

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;

/**
 * <b>@Desc</b>:   1、继承RequestInterceptor,把header设置到请求中,注意header的key若是大写时,请求中会被转为小写
 * <b>@Author</b>: hesh
 * <b>@Date</b>:   2020/6/21
 * <b>@Modify</b>:
 */
@Configuration
public class FeignConfig implements RequestInterceptor {
   

    @Override
    public void apply(RequestTemplate requestTemplate) {
   
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //当主线程的请求执行完毕后,Servlet容器会被销毁当前的Servlet,因此在这里需要做判空
        if (attributes != null) {
   
            HttpServletRequest request = attributes.getRequest();

            Enumeration<String> headerNames = request.getHeaderNames();

            while (headerNames.hasMoreElements()) {
   
                String name = headerNames.nextElement();
                //不能把所有消息头都传递下去,否则会引起其他异常;header的name都是小写
                if (name.equals("feignheader")) {
   
                    requestTemplate.header(name,request.getHeader(name));
                }
            }
        }
    }

}

2、修改 hystrix 的隔离策略为 semaphore

RequestContextHolder.getRequestAttributes()方法,实际上是从ThreadLocal变量中取得相应信息的。hystrix断路器的默认隔离策略为THREAD,该策略是无法取得ThreadLocal值的,所以需要修改hystrix的隔离策略,一般是改为[semaphore],在服务A中的 yml 新增配置如下

#2、hystrix 的隔离策略改为 SEMAPHORE
hystrix:
  command:
    default:
      execution:
        timeout:
          enable: true
        isolation:
          strategy: SEMAPHORE
          thread:
            timeoutInMilleseconds: 60000
3、客户端A的测试代码
3.1、服务A的controller接口
package com.he.feign.controller;

import com.he.feign.feign.HeaderFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * <b>@Desc</b>:   测试
 * <b>@Author</b>: hesh
 * <b>@Date</b>:   2020/6/21
 * <b>@Modify</b>:
 */
@Slf4j
@RequestMapping("/test_header")
@RestController
public class TestHeaderController {
   

    @Autowired
    private HeaderFeign headerFeign;

    @Autowired
    private HttpServletRequest servletRequest;//请求需要带请求头(key-value): feignheader-test

    @GetMapping("/main_thread")
    public String mainThread() {
   
        String resp = headerFeign.test();
        log.info("resp: {}", resp);
        return resp;
    }

    @GetMapping("/sub_thread")
    public void subThread() {
   
        new Thread(() -> {
   
            String resp = headerFeign.test();
            log.info("resp: {}", resp);
        }).start();
    }

    @GetMapping("/sub_thread/block")
    public String subThreadBlock() {
   
        //在主线程阻塞等待结果,由于请求仍有效没执行完毕,此时Servlet容器不会销毁HttpServletRequest,
        //所以请求属性还保存在请求链路中,能被传递下去
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> headerFeign.test());
        String resp = null;
        try {
   
            resp = future.get();
        } catch (InterruptedException e) {
   
            e.printStackTrace();
        } catch (ExecutionException e) {
   
            e.printStackTrace();
        }
        log.info("resp: ", resp);
        return resp;
    }
}

3.2、Feign类

feignclient的注解可以省略configuration配置,即configuration = FeignConfig.class可不声明

package com.he.feign.feign;

import com.he.feign.feign.hystrix.HeaderFeignFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * <b>@Desc</b>:   TODO
 * <b>@Author</b>: hesh
 * <b>@Date</b>:   2020/6/21
 * <b>@Modify</b>:
 */
//@FeignClient(value = &
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值