Feign替代RestTemplate,是一个声明式的http客户端。
官方地址:
https://github.com/OpenFeign/feign
使用
依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
启动类添加@EnableFeignClients注解:
编写Feign客户端,添加@FeignClien注解:
@FeignClient("userservice")
public interface UserClient {
@GetMapping("/user/{id}")
User findById(@PathVariable("id") Long id);
}
代替RestTemplate
自定义Feign的配置
feign.Logger.Level 修改日志级别 包含四种不同的级别:NONE、BASIC、HEADERS、FULL
feign.codec.Decoder 响应结果的解析器 http远程调用的结果做解析,例如解析json字符串为java对象
feign.codec.Encoder 请求参数编码 将请求参数编码,便于通过http请求发送
feign. Contract 支持的注解格式 默认是SpringMVC的注解
feign. Retryer 失败重试机制 请求失败的重试机制,默认是没有,不过会使用Ribbon的重试
配置Feign日志有两种方式:
方式一:配置文件方式
全局生效:
feign:
client:
config:
default: # 这里用default就是全局配置,如果是写服务名称,则是针对某个微服务的配置 loggerLevel: FULL # 日志级别
指定生效服务:
feign:
client:
config:
userservice:
loggerLevel: FULL # 日志级别
方式二:java代码方式,需要先声明一个Bean:
public class FeignClientConfiguration {
@Bean
public Logger.Level feignLogLevel(){
return Logger.Level.BASIC;
}
}
全局配置:启动类上@EnableFeignClients注解配置
@EnableFeignClients(defaultConfiguration = FeignClientConfiguration.class)
局部配置:@FeignClient注解上配置
@FeignClient(value = "userservice", configuration = FeignClientConfiguration.class)
Feign的性能优化
Feign底层的客户端实现:
URLConnection:默认实现,不支持连接池
Apache HttpClient :支持连接池
OKHttp:支持连接池
所以:
使用连接池代替默认的URLConnection
另外日志级别,最好用basic或none
Feign的性能优化-连接池配置
添加HttpClient的支持:
httpClient的依赖
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
配置日志级别BASIC 和连接池:
feign:
client:
config:
default: # default全局的配置
loggerLevel: BASIC # 日志级别,BASIC就是基本的请求和响应信息
httpclient:
enabled: true # 开启feign对HttpClient的支持
max-connections: 200 # 最大的连接数
max-connections-per-route: 50 # 每个路径的最大连接数
Feign的实践方案
抽取父接口:
降低耦合:提供方和消费方,controller层和client有很多代码耦合,可以抽取出公共接口。
抽取Client为独立模块,供消费者调用。
拓展
当定义的FeignClient不在SpringBootApplication的扫描包范围时,这些FeignClient无法使用。
两种解决方式:
方式一:指定FeignClient所在包:
@EnableFeignClients(basePackages = "cn.xxz.feign.clients")
方式二:指定FeignClient字节码
@EnableFeignClients(clients = {UserClient.class})