一、Fegin的使用
1、在一个微服务下引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2、添加注解
在启动类上加注解@EnableFeginClients开启Fegin
3、添加一个接口,编写fegin客户端
如:
@FeignClient("userservice")
public interface UserClient {
@GetMapping("/user/{id}")
User findById(@PathVariable("id") Long id);
}
总结:Fegin就是提取一个微服务中接口,封装成一个通用的接口,供其他微服务使用。
二、Fegin使用优化
Feign底层发起http请求,依赖于其它的框架。其底层客户端实现包括:
•URLConnection:默认实现,不支持连接池
•Apache HttpClient :支持连接池
•OKHttp:支持连接池
1、引入依赖
使用Apache HttpClient
<!--httpClient的依赖 -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
2、配置连接池
在application.yml中添加配置
feign:
client:
config:
default: # default全局的配置
loggerLevel: BASIC # 日志级别,BASIC就是基本的请求和响应信息,推荐使用
httpclient:
enabled: true # 开启feign对HttpClient的支持
max-connections: 200 # 最大的连接数
max-connections-per-route: 50 # 每个路径的最大连接数
总结:1.日志级别尽量用basic
2.使用HttpClient或OKHttp代替URLConnection
① 引入feign-httpClient依赖
② 配置文件开启httpClient功能,设置连接池参数
三、最佳实践
1、继承方式
服务提供者
public interface UserApi {
@GetMapper("user/{id}")
User findById(@PathVariable("id") Long id);
}
Fegin客户端,继承。消费者,调用Fegin客户端接口
@FeginClient(value = "userservice")
public interface UserClient extends UserApi{}
2、抽取
将Fegin的Client抽取成独立的微服务模块,并将有关的实体放到fegin-api模块中。
引入模块依赖,进行远程调用。