标签: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