Feign是简化Java HTTP客户端开发的工具(java-to-httpclient-binder),它的灵感来自于Retrofit、JAXRS-2.0和WebSocket。Feign的初衷是降低统一绑定Denominator到HTTP API的复杂度,不区分是否为restful。
添加依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring‐cloud‐starter‐openfeign</artifactId>
</dependency>
启动类添加注解
@EnableDiscoveryClient
@EnableFeignClients
创建client包
创建接口
@FeignClient("API‐base") //从哪个服务中调用功能 ,注意 里面的名称与被调用的服务名保持一致,并且不能包含下划线
public interface LabelClient {
@RequestMapping(value="/test/{id}", method = RequestMethod.GET) //@RequestMapping注解用于对被调用的微服务进行地址映射。注意 @PathVariable注解一定要指定参数名称,否则出错
public Result findById(@PathVariable("id") String id); }
调用
@Autowired private LabelClient labelClient;
@RequestMapping(value = "/test/{testid}") public Result findById(@PathVariable String testid){ Result result = labelClient.findById(labelid);
return result;
}
feign集成了负载均衡
请求压缩
Spring Cloud Feign 支持对请求和响应进行GZIP压缩,以减少通信过程中的性能损耗。通过下面的参数即可开启请求与响应的压缩功能:
feign: compression: request: enabled: true # 开启请求压缩 response: enabled: true # 开启响应压缩
可以对请求的数据类型,以及触发压缩的大小下限进行设置:
feign: compression: request: enabled: true # 开启请求压缩 mime-types: text/html,application/xml,application/json # 设置压缩的数据类型 min-request-size: 2048 # 设置触发压缩的大小下限