Feign的拦截器RequestInterceptor
SpringCloud的微服务使用Feign进行服务间调用的时候可以使用RequestInterceptor统一拦截请求来完成设置header等相关请求,但RequestInterceptor和ClientHttpRequestInterceptor有点不同,它拿不到原本的请求,所以要通过其他方法来获取原本的请求
首先创建自定义的RequestInterceptor
这里通过RequestContextHolder获取到当前的request
@Slf4j
@Component
public class MyFeignInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate template) {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
log.info("===request: {}", template.url());
template.header("aaaa", "bbbb");
}
}
然后定义一个feign的接口类
@FeignClient(name = "SPRING-CLOUD-CLIENT-DEMO")
public interface ClientFeign {
@GetMapping("/demo/get")
String weight(@RequestParam String param);
}
再创建一个controller
@Slf4j
@RestController
@RequestMapping("/interceptor")
public class InterceptorController {
@Autowired
private ClientFeign clientFeign;
@GetMapping("/feign")
public String feign(@RequestParam String param) {
return clientFeign.weight(param);
}
}
运行程序测试一下接口
查看程序打印
可以看到进入了我们自定义的RequestInterceptor
INFO 25936 --- [ctor-http-nio-3] c.m.d.g.interceptor.MyFeignInterceptor : ===request: /demo/weight?param=a
再查看feign调用的程序日志,可以看到设置的header信息
INFO 1 --- [nio-8801-exec-6] c.m.d.client.controller.DemoController : aaaa: a
INFO 1 --- [nio-8801-exec-6] c.m.d.client.controller.DemoController : websession: ECF4D97D02EEAFDDA3C15A7F1F050F61
INFO 1 --- [nio-8801-exec-6] c.m.d.client.controller.DemoController : header: aaaa, bbbb
INFO 1 --- [nio-8801-exec-6] c.m.d.client.controller.DemoController : header: accept, */*
INFO 1 --- [nio-8801-exec-6] c.m.d.client.controller.DemoController : header: user-agent, Java/1.8.0_191
INFO 1 --- [nio-8801-exec-6] c.m.d.client.controller.DemoController : header: host, 39.108.15.147:8801
INFO 1 --- [nio-8801-exec-6] c.m.d.client.controller.DemoController : header: connection, keep-alive