一、RestTemplate存在问题
观察之前文章介绍的远程调用的代码:
ini
复制代码
public OrderInfo selectOrderById(Integer orderId) {
OrderInfo orderInfo = orderMapper.selectOrderById(orderId);
String url = "http://product-service/product/"+ orderInfo.getProductId();
ProductInfo productInfo = restTemplate.getForObject(url,
ProductInfo.class);
orderInfo.setProductInfo(productInfo);
return orderInfo;
}
AI写代码java
运行
12345678
虽说RestTemplate 对HTTP封装后, 已经比直接使用[HTTPClient]简单方便很多, 但是还存在一些问题.
- 需要拼接URL, 灵活性高, 但是封装臃肿, URL复杂时, 容易出错.
- 代码可读性差, 风格不统⼀.
微服务\]之间的通信方式, 通常有两种: RPC 和 HTTP.
在SpringCloud中, 默认是使用HTTP来进行微服务的通信, 最常用的实现形式有两种:
• RestTemplate
• OpenFeign
## [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")二、OpenFeign介绍
OpenFeign 是一个声明式的 Web Service 客户端. 它让微服务之间的调用变得更简单, 类似controller调用service, 只需要创建⼀个接口,然后添加注解即可使用OpenFeign.
**OpenFeign 的前身**
Feign 是 Netflix 公司开源的⼀个组件.
• 2013年6月, Netflix发布 Feign的第⼀个版本 1.0.0
• 2016年7月, Netflix发布Feign的最后⼀个版本 8.18.0
2016年,Netflix 将 Feign 捐献给社区
• 2016年7月 OpenFeign 的首个版本 9.0.0 发布,之后⼀直持续发布到现在.
**Spring Cloud Feign**
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。
## [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")三、快速上手
### [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")3.1 引入依赖
```xml
org.springframework.cloud
spring-cloud-starter-openfeign
AI写代码java
运行
1234
```
### [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")3.2 添加注解
在order-service的启动类添加注解 @EnableFeignClients , 开启OpenFeign的功能.
```less
@EnableFeignClients
@SpringBootApplication
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
AI写代码java
运行
1234567
```
### [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")3.3 编写OpenFeign的客户端
基于SpringMVC的注解来声明远程调用的信息
```less
@FeignClient(value = "product-service", path = "/product")
public interface ProductApi {
@RequestMapping("/{productId}")
ProductInfo getProductById(@PathVariable("productId") Integer productId);
}
AI写代码java
运行
12345
```
@FeignClient 注解作用在接口上, 参数说明:
> • name/value:指定FeignClient的名称, 也就是微服务的名称, 用于服务发现, Feign底层会使用Spring Cloud LoadBalance进行负载均衡. 也可以使用 url 属性指定⼀个具体的url.
>
> • path: 定义当前FeignClient的统一前缀.
### [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")3.4 远程调用
修改远程调用的方法
```ini
@Autowired
private ProductApi productApi;
/**
* Feign实现远程调⽤
* @param orderId
*/
public OrderInfo selectOrderById(Integer orderId) {
OrderInfo orderInfo = orderMapper.selectOrderById(orderId);
ProductInfo productInfo =
productApi.getProductById(orderInfo.getProductId());
orderInfo.setProductInfo(productInfo);
return orderInfo;
}
AI写代码java
运行
12345678910111213
```
不同方式之间代码对比:

## [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")四、OpenFeign参数传递
通过观察, 我们也可以发现, Feign的客户端和服务提供者的接口声明非常相似
上面例子中, 介绍了Feign 从URL中获取参数, 接下来介绍下Feign参数传递的其他方式。
### [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")4.1 传递单个参数
服务提供方:product-service
```less
@RequestMapping("/product")
@RestController
public class ProductController {
@RequestMapping("/p1")
public String p1(Integer id){
return "p1接收到参数:"+id;
}
}
AI写代码java
运行
12345678
```
Feign客户端:
```less
@FeignClient(value = "product-service", path = "/product")
public interface ProductApi {
@RequestMapping("/p1")
String p1(@RequestParam("id") Integer id);
}
AI写代码java
运行
12345
```
服务消费方order-service:
```less
@RequestMapping("/feign")
@RestController
public class TestFeignController {
@Autowired
private ProductApi productApi;
@RequestMapping("/o1")
public String o1(Integer id){
return productApi.p1(id);
}
}
AI写代码java
运行
12345678910
```
### [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")4.2 传递多个参数
使用多个@RequestParam 进行参数绑定即可
服务提供方 product-service
```typescript
@RequestMapping("/p2")
public String p2(Integer id,String name){
return "p2接收到参数,id:"+id +",name:"+name;
}
AI写代码java
运行
1234
```
Feign客户端:
```less
@FeignClient(value = "product-service", path = "/product")
public interface ProductApi {
@RequestMapping("/p2")
String p2(@RequestParam("id")Integer id,@RequestParam("name")String name);
}
AI写代码java
运行
12345
```
服务消费方order-service:
```less
@RequestMapping("/o2")
public String o2(@RequestParam("id")Integer id,@RequestParam("name")String name){
return productApi.p2(id,name);
}
AI写代码java
运行
1234
```

### [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")4.3 传递对象
服务提供方 product-service
```typescript
@RequestMapping("/p3")
public String p3(ProductInfo productInfo){
return "接收到对象, productInfo:"+productInfo;
}
AI写代码java
运行
1234
```
Feign客户端:
```less
@RequestMapping("/p3")
String p3(@SpringQueryMap ProductInfo productInfo);
AI写代码java
运行
12
```
服务消费方order-service:
```typescript
@RequestMapping("/o3")
public String o3(ProductInfo productInfo){
return productApi.p3(productInfo);
}
AI写代码java
运行
1234
```
### [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")4.4 传递JSON
服务提供方 product-service:
```less
@RequestMapping("/p4")
public String p4(@RequestBody ProductInfo productInfo){
return "接收到对象, productInfo:"+productInfo;
}
AI写代码java
运行
1234
```
Feign客户端
```less
@RequestMapping("/p4")
String p4(@RequestBody ProductInfo productInfo);
AI写代码java
运行
12
```
服务消费方order-service:
```less
@RequestMapping("/o4")
public String o4(@RequestBody ProductInfo productInfo){
System.out.println(productInfo.toString());
return productApi.p4(productInfo);
}
AI写代码java
运行
12345
```
## [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")五、最佳实践
最佳实践, 其实也就是经过历史的迭代, 在项目中的实践过程中, 总结出来的最好的使用方式.
通过观察, 我们也能看出来, Feign的客户端与服务提供者的controller代码非常相似
Feign 客户端:
```less
@FeignClient(value = "product-service", path = "/product")
public interface ProductApi {
@RequestMapping("/{productId}")
ProductInfo getProductById(@PathVariable("productId") Integer productId);
}
AI写代码java
运行
12345
```
服务提供方Controller:
```less
@RequestMapping("/product")
@RestController
public class ProductController {
@RequestMapping("/{productId}")
public ProductInfo getProductById(@PathVariable("productId") Integer productId){
//...
}
}
AI写代码java
运行
12345678
```
有没有⼀种方法可以简化这种写法呢?
### [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")5.1 Feign继承方式
Feign 支持继承的方式, 我们可以把⼀些常件的操作封装到接口里.
我们可以定义好⼀个接口, 服务提供方实现这个接口, 服务消费方编写Feign 接口的时候, 直接继承这个接口
#### [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")5.1.1 创建一个Module
接口可以放在⼀个公共的Jar包里, 供服务提供方和服务消费方使用

#### [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")5.1.2 引入依赖
```xml
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-openfeign
AI写代码java
运行
12345678910
```
#### [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")5.1.3 编写接口
复制 ProductApi, ProductInfo 到product-api模块中
```less
public interface ProductInterface {
@RequestMapping("/{productId}")
ProductInfo getProductById(@PathVariable("productId") Integer productId);
@RequestMapping("/p1")
String p1(@RequestParam("id") Integer id);
@RequestMapping("/p2")
String p2(@RequestParam("id")Integer id,@RequestParam("name")String name);
@RequestMapping("/p3")
String p3(@SpringQueryMap ProductInfo productInfo);
@RequestMapping("/p4")
String p4(@RequestBody ProductInfo productInfo);
}
AI写代码java
运行
123456789101112
```
### [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")5.1.5 服务提供方
服务提供方实现接口ProductInterface:
```typescript
@RequestMapping("/product")
@RestController
public class ProductController implements ProductInterface {
@Autowired
private ProductService productService;
@RequestMapping("/{productId}")
public ProductInfo getProductById(@PathVariable("productId") Integer
productId){
System.out.println("收到请求,Id:"+productId);
return productService.selectProductById(productId);
}
@RequestMapping("/p1")
public String p1(Integer id){
return "p1接收到参数:"+id;
}
@RequestMapping("/p2")
public String p2(Integer id,String name){
return "p2接收到参数,id:"+id +",name:"+name;
}
@RequestMapping("/p3")
public String p3(ProductInfo productInfo){
return "接收到对象, productInfo:"+productInfo;
}
@RequestMapping("/p4")
public String p4(@RequestBody ProductInfo productInfo){
return "接收到对象, productInfo:"+productInfo;
}
}
AI写代码java
运行
12345678910111213141516171819202122232425262728
```
#### [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")5.1.6 服务消费方
服务消费方继承ProductInterface
```kotlin
@FeignClient(value = "product-service", path = "/product")
public interface ProductApi extends ProductInterface {
}
AI写代码java
运行
123
```
这样通过继承就可以实现远程调用
### [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")5.2 Feign 抽取方式
官方推荐Feign的使用方式为继承的方式, 但是企业开发中, 更多是把Feign接口抽取为⼀个独立的模块(做法和继承相似, 但理念不同).
操作方法:
将Feign的Client抽取为⼀个独立的模块, 并把涉及到的实体类等都放在这个模块中, 打成⼀个Jar. 服务消费方只需要依赖该Jar包即可. 这种方式在企业中比较常见, Jar包通常由服务提供方来实现.
#### [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")5.2.1 创建新module

#### [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")5.2.2 引入依赖
```xml
org.springframework.cloud
spring-cloud-starter-openfeign
AI写代码java
运行
1234
```
#### [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")5.2.3 编写API
复制 ProductApi, ProductInfo 到product-api模块中
之后通过Maven打包,可以观察Maven本地仓库检查是否打包成功
#### [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")5.2.4 服务消费方使用product-api
1 删除 ProductApi, ProductInfo.
2. 引入依赖:
```xml
org.example
product-api
1.0-SNAPSHOT
AI写代码java
运行
12345
```
修改项目中ProductApi, ProductInfo的路径为product-api中的路径
3 .指定扫描类: ProductApi
在启动类添加扫描路径
```less
@EnableFeignClients(basePackages = {"com.bite.api"})
@SpringBootApplication
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
AI写代码java
运行
1234567
```
> 也可以指定需要加载的Feign客户端
> `@EnableFeignClients(clients = {ProductApi.class})`
## [](https://link.juejin.cn?target= "")[](https://link.juejin.cn?target= "")六、总结
以上就是本文全部内容,本文主要为大家介绍了Spring Cloud中实现远程调用的另一个组件-OpenFeign的相关知识与操作。感谢各位能够看到最后,如有问题,欢迎各位大佬在评论区指正,希望大家可以有所收获!创作不易,希望大家多多支持。