场景:A模块,要通过feign调另外一个模块B的接口,同时要把请求A模块的请求头参数header 传给B
模块B: controller中的一个方法
@Override
@PostMapping("/list/{page}/{size}")
public QueryResponseResult findList(@PathVariable("page") int page,@PathVariable("size") int size,@RequestBody QueryLostRequest queryLostRequest) {
//获取头信息
String authorization = request.getHeader("Authorization");
System.out.println("authorization = " + authorization);
return lostService.filterList(page - 1, size, queryLostRequest);
}
模块A:Bclient
@FeignClient(value = "B",configuration = FeignConfig.class)
public interface Blient {
@PostMapping("/lost/list/{page}/{size}")
public QueryResponseResult findList(@PathVariable("page") int page, @PathVariable("size") int size, @RequestBody QueryLostRequest queryLostRequest);
}
模块A: 自己写一个FeignConfig类,实现RequestInterceptor接口
@Configuration
public class FeignConfig implements RequestInterceptor {
@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);
}
}
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());
}
}
}
模块A: application.yml
feign:
hystrix:
enabled: true
client:
config:
default:
connectTimeout: 60000
readTimeout: 60000
hystrix:
command:
default:
execution:
timeout:
enabled: true
isolation:
strategy: SEMAPHORE
thread:
timeoutInMilliseconds: 60000
大功告成。
总结:
1.需要在配置文件写相应的配置信息
2.自己写一个feignconfig
3.在@FeignClient上加,configuration = FeignConfig.class