springCloud-Feign 拦截器使用,传递header中的值

时间:2024-04-20 07:05:17

场景:服务A 调用 服务B

1 编写拦载器类

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;


public class Interceptor_a implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        System.err.println("拦截器");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        template.header("code",request.getHeader("code"));
    }
}

使用拦截器,两种方法,选一种即可

//方法1
@FeignClient(value= "app_b",
        path = "/dts_address",
        configuration = Interceptor_a.class
)
#方法2
feign:
  sentinel:
    enabled: true
  client:
    config:
      app_b:
        # 配置拦截器
        request-interceptors:
          - org.example.Interceptor_a
      default:
        logger-level: full
        connect-timeout: 10000
        read-timeout: 10000
logging:
  level:
    cn.haiwang: debug

3 测试,服务A发请示时,在header中设置参数code,服务B可以拿到拦截器里设置的信息

/*
服务b 工程的代码
*/
@RequestMapping(value="/add")
    public Object add(@RequestBody DtsAddress dtsAddress
                      ){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements())
        {
            String s = headerNames.nextElement();
            String header = request.getHeader(s);
            System.err.println(s+" : "+header);
        }
      
    }