说明:
于feign 请求底层是通过 RestTemplate 进行请求,Feign 支持请求拦截器,在发送请求前,可以对发送的模板进行操作,例如设置请求头等属性,
自定请求拦截器需要实现 feign.RequestInterceptor 接口,该接口的方法 apply 有参数 template ,该参数类型为 RequestTemplate,我们可以根据实际情况对请求信息进行调整。
1.通过拦截器配置,如果要区分进行判断就行,然后注册一下拦截器就可以使用了。
@Configuration
public class FeignConfiguration 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());
}
}
}
2.使用
@FeignClient(value = "client-homepage-course", fallback = CourseClientHystrix.class,configuration = FeignConfiguration.class)
public interface CourseClient {
@RequestMapping(value = "/homepage-course/get/courses", method = RequestMethod.POST)
List<CourseInfo> getCourseInfos(@RequestBody CourseInfosRequest request);
}
PS:
在服务中配置 FeignConfiguration 时,上面的代码示例是通过 RequestContextHolder.getRequestAttributes() 解析到当前请求头的参数,
RequestContextHolder是基于ThreadLocal实现的,所以需要保证请求是一直处于同一个线程当中,hystrix强大在于是支持此扩展操作的。
另一种解决方案:由于所解析的模块没有添加spring-web相关的依赖配置,无法使用 RequestContextHolder ,使用 过滤器过滤出当前
线程中的请求头,并保存到ThreadLocal 中,在 FeignConfiguration 中解析 保存在ThreadLocal中的消息头参数,然后设置消息头给RestTemplate.
3.使用固定headers ,@RequestMapping或其派生注解的header属性中解析Header的,并且Header的key和value需要用“=”进行分割。
@GetMapping(value = "/api/clusterManager/listTopics",
headers = {"cache-control=no-cache", "username=wangyong@xxx.com"})
TopicsResponse listTopics(@RequestParam("clusterName") String clusterName,
@RequestParam("clusterArea") String clusterArea);
更多内容请关注: