码迷,mamicode.com
首页 > 编程语言 > 详细

Spring Cloud之Feign 转发请求头(header参数)

时间:2018-10-10 14:32:58      阅读:924      评论:0      收藏:0      [点我收藏+]

标签:div   The   获取   pre   etc   str   buffer   elements   value   

在做接口请求时,我们经常会在header头中增加一些鉴权信息,如token 或 jwt,那么在通过fegin从A server去调用B server的接口时,如果B server的接口需要header信息,我们需要将A sever获取的header转发到B上。

解决方式

我们需要实现Feign提供的一个接口RequestInterceptor

@Configuration
public class FeignConfiguration implements RequestInterceptor{
    private final Logger logger = LoggerFactory.getLogger(getClass());

            @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);

                    }
                    logger.info("feign interceptor header:{}",template);
                }
               /* 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());
                    //logger.info("feign interceptor body:{}",body.toString());
                }*/
            }
        }

@FeignClient注解里面的属性加上configuration = FeignConfiguration.class就可以了。如

@FeignClient(name = "a-server",  configuration = FeignConfiguration.class)
public interface AServer{
}

 

bootstrap.yml增加

hystrix:
  command:
    default:
      execution:
        timeout:
          enabled: false
        isolation:
          strategy: SEMAPHORE

 

Spring Cloud之Feign 转发请求头(header参数)

标签:div   The   获取   pre   etc   str   buffer   elements   value   

原文地址:https://www.cnblogs.com/tulu/p/9765675.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!