openFeign实现服务间并且调用时传递header以及新增header, header透传
场景:A服务调用B服务,并且在进入到B服务之前,设置一个自定义的hader值,实现如下:
1、创建FeignConfiguration:
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
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;
@Configuration
public class FeignConfiguration implements RequestInterceptor {
/**
* 设置header传递,将当前服务的header信息传递到下游服务
*
* @param template
*/
@Override
public void apply(RequestTemplate template) {
ServletRequestAttributes attributes = (ServletRequestAttributes)
RequestContextHolder.getRequestAttributes();
if (attributes != null) {
HttpServletRequest request = attributes.getRequest();
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
String values = request.getHeader(name);
// 跳过 content-length
if ("content-length".equals(name)) {
continue;
}
template.header(name, values);
}
}
template.header("test-header", "123456");
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
2、配置@FeignClient:
在@FeignClient注解中,指定配置文件
@FeignClient(value = "b-service",
configuration = {FeignErrorDecoder.class}
)
public interface WageServiceFeign {
......
}
1
2
3
4
5
6
3、测试:
在A服务的feign配置文件通过template.header("test-header", "123456");设置了一个header,我们在B服务的Controller中,测试是否能够获取
————————————————
版权声明:本文为CSDN博主「一恍过去」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zhuocailing3390/article/details/123214433