目录
1.OpenFeign
在之前的远程调用代码中,我们是利用Nacos实现了服务的治理,利用RestTemplate实现了服务的远程调用。但是远程调用的代码太复杂了:
其实远程调用的关键点就在于四个:
- 请求方式
- 请求路径
- 请求参数
- 返回值类型
于是引出了一个新的技术:OpenFeign,来简化远程调用的代码。
1.1快速入门
OpenFeign已经被SpringCloud自动装配,实现起来非常简单:
(1)引入依赖,包括OpenFeign和负载均衡组件SpringCloudLoadBalancer
<!--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)在cart-service
的CartApplication
启动类上添加@EnableFeignClients注解,开启OpenFeign功能(3)新开一个client包,添加ItemClient接口,编写FeignClient客户端
package com.hmall.cart.client;
import com.hmall.cart.domain.dto.ItemDTO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
@FeignClient("item-services")
public interface ItemClient {
@GetMapping("/items")
List<ItemDTO> queryItemByIds(@RequestParam("ids") Collection<Long> ids);
}
这里只需要声明接口,无需实现方法。接口中的几个关键信息:
- @FeignClient("item-service") :声明服务名称
- @GetMapping("/items") :声明请求方式和路径
- @RequestParam("ids") Collection<Long> ids :声明请求参数
- List<ItemDTO> :返回值类型
有了上述信息,OpenFeign就可以利用动态代理帮我们实现这个方法,并且向http://item-service/items
发送一个GET
请求,携带ids为请求参数,并自动将返回值处理为List<ItemDTO>
。
我们只需要直接调用这个方法,即可实现远程调用了。
(4)在cart-service
的CartServiceImpl