本文主要是介绍Feign的拦截器RequestInterceptor,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Feign的拦截器RequestInterceptor
SpringCloud的微服务使用Feign进行服务间调用的时候可以使用RequestInterceptor统一拦截请求来完成设置header等相关请求,但RequestInterceptor和ClientHttpRequestInterceptor有点不同,它拿不到原本的请求,所以要通过其他方法来获取原本的请求
首先创建自定义的RequestInterceptor
这里通过RequestContextHolder获取到当前的request
@Slf4j
@Component
public class MyFeignInterceptor implements RequestInterceptor {@Overridepublic 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 {@Autowiredprivate 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: aINFO 1 --- [nio-8801-exec-6] c.m.d.client.controller.DemoController : websession: ECF4D97D02EEAFDDA3C15A7F1F050F61INFO 1 --- [nio-8801-exec-6] c.m.d.client.controller.DemoController : header: aaaa, bbbbINFO 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_191INFO 1 --- [nio-8801-exec-6] c.m.d.client.controller.DemoController : header: host, 39.108.15.147:8801INFO 1 --- [nio-8801-exec-6] c.m.d.client.controller.DemoController : header: connection, keep-alive
欢迎关注微信交流
这篇关于Feign的拦截器RequestInterceptor的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!