简单使用
前面的文章示例已简单介绍openfeign的使用,各位可再去看《SpringCloudAlibaba注册中心与配置中心之利器Nacos实战与源码分析(中)》文章中的内容,大致的步骤为Pom文件加spring-cloud-starter-openfeign启动器依赖、加注解加配置、最后SpringBoot启动类上加启用注解@EnableFeignClients就完成。而Spring MVC注解风格的不同类型请求方法使用示例如下:
@FeignClient("stores") public interface StoreClient { @RequestMapping(method = RequestMethod.GET, value = "/stores") List<Store> getStores(); @RequestMapping(method = RequestMethod.GET, value = "/stores") Page<Store> getStores(Pageable pageable); @RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json") Store update(@PathVariable("storeId") Long storeId, Store store); @RequestMapping(method = RequestMethod.DELETE, value = "/stores/{storeId:\\d+}") void delete(@PathVariable Long storeId); }
关于Spring Cloud OpenFeign配置属性的列表详细可查看 下方公众号 。而常见的配置属性如下:
feign: client: config: feignName: connectTimeout: 5000 readTimeout: 5000 loggerLevel: full errorDecoder: com.example.SimpleErrorDecoder retryer: com.example.SimpleRetryer defaultQueryParameters: query: queryValue defaultRequestHeaders: header: headerValue requestInterceptors: - com.example.FooRequestInterceptor - com.example.BarRequestInterceptor decode404: false encoder: com.example.SimpleEncoder decoder: com.example.SimpleDecoder contract: com.example.SimpleContract capabilities: - com.example.FooCapability - com.example.BarCapability queryMapEncoder: com.example.SimpleQueryMapEncoder metrics.enabled: false
契约配置
如果我们项目原来是使用NetFlix的原生Feign注解进行开发,在OpenFeign中可无需修改Feign原生注解,只需进行配置就可以轻易兼容原来代码无需整改。前面文章示例使用OpenFeign声明代码如下
package cn.itxs.ecom.commons.service.openfeign; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @FeignClient("ecom-storage-service") public interface StorageFeignService { @RequestMapping("/deduct/{commodityCode}/{count}") String deduct(@PathVariable("commodityCode") String commodityCode, @PathVariable("count") int count); }
- 修改契约配置,支持Feign原生注解(推荐)
创建FeignConfiguratio