发布于 

FeignConfig调用携带本次请求的请求头信息

创建FeignConfig

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
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
* 设置Feign调用请求头信息
*/
@Slf4j
public class FeignConfig implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
// try起来防止由于设备上报的信息没有请求头信息导致报错,调用失败
try {
// 获取当前请求头信息
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//传递header里面所有内容
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
String values = request.getHeader(name);
// 跳过 content-length ,不跳过会导致feign.RetryableException: too many bytes written executing
if (name.equals("content-length")){
continue;
}
// 设置请求头信息
requestTemplate.header(name, values);
}
}
} catch (Exception e) {
log.info("设备上报调用,无请求头信息");
}

}
}

feign接口处添加注解参数

1
2
3
4
@FeignClient(configuration = FeignConfig.class)
public interface testService{

}

本站由 @binvv 使用 Stellar 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。