微服务通过feign.RequestInterceptor传递参数

Feign 支持请求拦截器,在发送请求前,可以对发送的模板进行操作,例如设置请求头等属性,自定请求拦截器需要实现 feign.RequestInterceptor 接口,该接口的方法 apply 有参数 template ,该参数类型为 RequestTemplate,我们可以根据实际情况对请求信息进行调整,示例如下:

  • 创建自定义请求拦截器,在发送请求前增加了一个请求头信息,进行身份校验。

具体代码参考如下:

import feign.RequestInterceptor;

import feign.RequestTemplate;

   

public class MyRequestInterceptor implements RequestInterceptor{

   

public void apply(RequestTemplatetemplate){

template.header("Authorization","123");

}

}

 服务端可以通过HttpServletRequest获取到前面传递的参数,具体获取逻辑如下:

 RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            request.getHeader("Authorization");
        }

 就实现了各个微服务之间参数的传递。 

猜你喜欢

转载自www.cnblogs.com/baizhanshi/p/10913590.html