使用 OpenFeign 实现服务间通信
前言
利用Nacos实现了服务的治理,利用RestTemplate实现了服务的远程调用。但是远程调用的代码太复杂:
这种调用方式,与原本的本地方法调用差异太大,编程时的体验也不统一,一会儿远程调用,一会儿本地调用。
因此,必须想办法改变远程调用的开发模式,让远程调用像本地方法调用一样简单。而这就要用到OpenFeign组件了。
其实远程调用的关键点就在于四个:
- 请求方式
- 请求路径
- 请求参数
- 返回值类型
所以,OpenFeign就利用SpringMVC的相关注解来声明上述4个参数,然后基于动态代理帮我们生成远程调用的代码,而无需我们手动再编写,非常方便。
1.导入依赖
在服务调用者cart-service服务的pom.xml中引入OpenFeign的依赖和loadBalancer依赖:
代码如下:
<!-- OpenFeign 依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- 负载均衡器依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
2.启用OpenFeign
接下来,我们在服务调用者cart-service的CartApplication启动类上添加注解,启动OpenFeign功能:
代码如下:
@EnableFeignClients
@SpringBootApplication
public class CartApplication {
public static void main(String[] args) {
SpringApplication.run(CartApplication.class, args);
}
}
3.编写OpenFeign客户端
定义一个新的接口,编写Feign客户端:
代码如下:
@FeignClient("item-service")
public interface ItemClient {
@GetMapping("/items")
List<ItemDTO> queryItemByIds(@RequestParam("ids") Collection<Long> ids);
}
这里只需要声明接口,无需实现方法。接口中的几个关键信息:
- @FeignClient(“item-service”) :声明服务名称
- @GetMapping :声明请求方式
- @GetMapping(“/items”) :声明请求路径
- @RequestParam(“ids”) Collection ids :声明请求参数
- List :返回值类型
有了上述信息,OpenFeign就可以利用动态代理帮我们实现这个方法,并且向http://item-service/items发送一个GET请求,携带ids为请求参数,并自动将返回值处理为List。
我们只需要直接调用这个方法,即可实现远程调用了。
4.使用FeignClient
最后,我们在cart-service的CartServiceImpl中改造代码,直接调用ItemClient的方法:
代码如下:
private final ItemClient itemClient;
private void handleCartItems(List<CartVO> vos) {
// 获取商品id
Set<Long> itemIds = vos.stream().map(CartVO::getItemId).collect(Collectors.toSet());
// 查询商品
List<ItemDTO> items = itemClient.queryItemByIds(itemIds);
}
feign替我们完成了服务拉取、负载均衡、发送http请求的所有工作。
而且,这里不再需要RestTemplate了,省去了RestTemplate的注册。
5.Feign底层http请求连接池改造
Feign底层发起http请求,依赖于其它的框架。其底层支持的http客户端实现包括:
- HttpURLConnection:默认实现,不支持连接池
- Apache HttpClient :支持连接池
- OKHttp:支持连接池
为了优化 Feign 的性能,可以使用 OkHttp 替换默认的HttpURLConnection客户端,并开启连接池
在cart-service的pom.xml中引入依赖:
<!--OK http 的依赖 -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
然后,在配置文件中开启连接池:
feign:
okhttp:
enabled: true # 开启OKHttp功能