为什么不再只用 RestTemplate
在微服务架构中,服务间通信通常基于 HTTP。虽然 RestTemplate 对 HTTP 进行了封装,比直接使用 HttpClient 方便许多,但在实际开发中仍暴露出一些问题。
比如需要手动拼接 URL,灵活性虽高但代码臃肿,URL 复杂时容易出错,且风格难以统一。我们来看一段典型的 RestTemplate 调用代码:
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;
}
这种写法不仅可读性差,还缺乏类型安全。Spring Cloud 生态中,除了 RestTemplate,更推荐的方式是使用 OpenFeign。
OpenFeign 简介
OpenFeign 是一个声明式的 Web Service 客户端。它让微服务之间的调用变得像本地方法调用一样简单,只需要创建一个接口并添加注解即可。
历史背景
Feign 最初由 Netflix 开源,2016 年捐赠给社区后演变为 OpenFeign。Spring Cloud 对其进行了封装,提供了 spring-cloud-starter-openfeign 依赖。
注意:由于原 Feign 项目已停止维护,现在应使用 Spring Cloud 提供的 OpenFeign 版本。
快速上手
1. 引入依赖
在消费方服务的 pom.xml 中添加以下依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2. 开启功能
在启动类上添加 @EnableFeignClients 注解:
@EnableFeignClients
@SpringBootApplication
{
{
SpringApplication.run(OrderServiceApplication.class, args);
}
}



