本文基于上一篇http://t.csdnimg.cn/0qm2R 的基础上添加OpenFeign的使用。
微服务通信
在微服务架构中,微服务之间的通信通常有两种方式:RPC 和 HTTP。在 Spring Cloud 中,默认使用 HTTP 进行微服务的通信,最常用的实现形式有两种:RestTemplate OpenFeign
HTTP 通信
RestTemplate
RestTemplate是 Spring 提供的用于同步 HTTP 请求的客户端工具,可以方便地与其他微服务进行 HTTP 调用。
OpenFeign
OpenFeign是一个声明式的 HTTP 客户端,使得编写 HTTP 客户端变得非常简单。通过注解来定义接口,Spring Cloud Feign 会自动生成实现该接口的 HTTP 客户端对象。
Netflix于2013年6月发布了Feign的第一个版本1.0.0,并于2016年7月发布了最后一个版本8.18.0。在2016年,Netflix将Feign捐献给社区,并于同年7月发布了OpenFeign的首个版本9.0.0,随后持续发布至今。因此,可以简单理解为Netflix Feign是OpenFeign的祖先,或者说OpenFeign是Netflix Feign的升级版。OpenFeign是Feign的一个更强大、更灵活的实现。(后续提到的Feign都是 OpenFeign)
Spring Cloud Feign 是 Spring 对 Feign 的封装,将 Feign 项目集成到 Spring Cloud 生态系统中。受 Feign 更名影响,Spring Cloud Feign 也有两个 starter:
spring-cloud-starter-feign
spring-cloud-starter-openfeign
由于 Feign 停更维护,因此我们使用的依赖是 spring-cloud-starter-openfeign。
RPC(Remote Procedure Call)
RPC(远程过程调用)是一种通过网络从远程计算机上请求服务,而不需要了解底层网络通信细节的机制。RPC 可以使用多种网络协议进行通信,如 HTTP、TCP、UDP 等,并且在 TCP/IP 网络四层模型中跨越了传输层和应用层。简而言之,RPC 就是像调用本地方法一样调用远程方法。
常见的 RPC 框架有:
1. Dubbo:是一个高性能的 Java RPC 框架,提供透明化的远程方法调用,主要用于构建分布式服务架构。
2. Thrift:是一个由 Facebook 开发的跨语言的 RPC 框架,支持多种编程语言,适用于服务之间高效的通信。
3. gRPC: gRPC 是 Google 开发的高性能、开源的 RPC 框架,使用 Protocol Buffers 作为接口描述语言,支持多种编程语言,适用于不同平台的服务通信。
通过上述工具和框架,可以实现微服务之间的高效通信,无论是通过 HTTP 还是 RPC,选择何种方式取决于具体的业务需求和技术选型。
OpenFeign的使用
引入依赖
在order-service的pom中引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
添加注解
在启动类中添加注解,开启feign功能。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableFeignClients # 开启openFeign功能
@SpringBootApplication
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
编写客户端
import com.demo.order.model.ProductInfo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
// name:根据注册中心的服务名来调用
// path:调用product-service中的controller中的所有url都有path前缀
@FeignClient(name = "product-service", path = "/product")
// 根据product-service中的controller中的接口写方法
public interface ProductApi {
// 与product-service中的controller中的接口相对应
@RequestMapping("/{productId}")
ProductInfo getProductById(@PathVariable("productId") Integer productId);
}
远程调用
import com.demo.order.api.ProductApi;
import com.demo.order.mapper.OrderMapper;
import com.demo.order.model.OrderInfo;
import com.demo.order.model.ProductInfo;
import org.springf