SpringBoot项目中feignClient使用方式
作者:三五二十五
文章介绍了在Spring Boot项目中配置Feign客户端拦截器的具体步骤,包括在application.yml中添加配置、在主类上启用组件扫描、将拦截器加入到拦截器列表中以及在接口调用时的说明,总结指出这是个人经验分享,希望对大家有所帮助
SpringBoot项目中feignClient使用
1.在application.yml中加入两个配置
# feign client 配置 hystrix: threadpool: default: coreSize: 500 maxQueueSize: -1 queueSizeRejectionThreshold: 10000 command: default: circuitBreaker: requestVolumeThreshold: 1500 execution: #(超时时间) timeout: enabled: false #(上下文传递) isolation: strategy: SEMAPHORE semaphore: maxConcurrentRequests: 1500 maxSemaphores: 1500 ribbon: ConnectTimeout: 50000000 ReadTimeout: 500000000
2.在主类上加入
scanBasePackageClasses = FeignInterceptor.class, scanBasePackages = {"com.example"}
FeignInterceptor用来扫描 传递上下文的拦截器 {"com.example"}用来扫描自己的包 @EnableFeignClients(主类上)扫描被@FeignClient注解的接口 @EnableFeignClients @SpringBootApplication(scanBasePackageClasses = FeignInterceptor.class, scanBasePackages = {"com.example"})
3.将xxxRestContextInterceptor加入到拦截器中
@Configuration public class WebAppConfig extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { //注册自定义拦截器,添加拦截路径和排除拦截路径 registry.addInterceptor(new XsyRestContextInterceptor()); } }
4.接口调用说明
声明一个接口比如:PaasAggFeignClient,在其上显式加上@FeignClient注解
内部填入Eureka上已注册服务名称比如:
@FeignClient("manager-service", configuration = FeignInterceptor.class)
其中configuration = FeignInterceptor.class是要加上的,保证FeignInterceptor生效
自定义方法,请求路径为该服务上对应的rest请求路径,如下
@FeignClient("manager-service") public interface PaasAggFeignClient { @RequestMapping(value = "/api/xxxx/test/description", method = RequestMethod.GET) String testDescription(); @RequestMapping(value = "/api/xxxx/test/{id}", method = RequestMethod.GET) String testInfo(@PathVariable("id") Long id); @RequestMapping(value = "/api/xxxx/test/", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON}) String testCreate(@RequestBody JSONObject jsonObject); @RequestMapping(value = "/api/xxxx/test/{id}", method = RequestMethod.DELETE) String testDelete(@PathVariable("id") Long id); @RequestMapping(value = "/api/xxxx/test/{id}", method = RequestMethod.PATCH, consumes = {MediaType.APPLICATION_JSON}) String testUpdate(@PathVariable("id") Long id, @RequestBody JSONObject jsonObject); }
5.在对应controller内引入自定义接口即可使用
@Resource private PaasAggFeignClient paasAggFeignClient; String paasAggResult = paasAggFeignClient.testDescription(); String paasAggResult = paasAggFeignClient.testCreate(entity); String paasAggResult = paasAggFeignClient.testDelete(id); .....
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。