原文地址:Spring Cloud 入门 之 Feign 篇(三)
博客地址:http://www.extlight.comjava
在上一篇文章《Spring Cloud 入门 之 Ribbon 篇(二)》 中介绍了 Ribbon 使用负载均衡调用微服务,但存在一个问题:消费端每一个请求方法中都须要拼接请求服务的 URL 地址,存在硬编码问题且不符合面向对象编程思想。若是服务名称发生变化,消费端也须要跟着修改。git
本篇文章将介绍 Feign 来解决上边的问题。github
Feign 是一个声明式的 Web Service 客户端。使用 Feign 能让编写 Web Service 客户端更加简单,同时支持与Eureka、Ribbon 组合使用以支持负载均衡。spring
Spring Cloud 对 Feign 进行了封装,使其支持了 Spring MVC 标准注解和 HttpMessageConverters。编程
Feign 的使用方法是定义一个接口,而后在其上边添加 @FeignClient 注解。api
本次测试案例基于以前发表的文章中介绍的案例进行演示,不清楚的读者请先转移至 《Spring Cloud 入门 之 Ribbon 篇(二)》 进行浏览。app
在 common-api 和 order-server 项目中添加依赖:负载均衡
<!-- feign --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
在 common-api 中项目中新建一个接口:ide
@FeignClient(value="GOODS") public interface GoodsServiceClient { @RequestMapping("/goods/goodsInfo/{goodsId}") public Result goodsInfo(@PathVariable("goodsId") String goodsId); }
使用 @FeignClient 注解指定调用的微服务名称,封装了调用 USER-API 的过程,做为消费方调用模板。微服务
注意:Feign 接口的定义最好与对外开发的 controller 中的方法定义一致,此处的定义与 goods-server 项目中 controller 类定义的方法一致。
在 order-server 项目中,使用 GoodsServiceClient 获取商品信息:
@Service public class OrderServiceImpl implements OrderService{ // @Autowired // private RestTemplate restTemplate; @Autowired private GoodsServiceClient goodsServiceClient; @Override public void placeOrder(Order order) throws Exception{ //Result result = this.restTemplate.getForObject("http://GOODS/goods/goodsInfo/" + order.getGoodsId(), Result.class); Result result = this.goodsServiceClient.goodsInfo(order.getGoodsId()); if (result != null && result.getCode() == 200) { System.out.println("=====下订单===="); System.out.println(result.getData()); } } }
直接使用 Feign 封装模板调用服务方,免去麻烦的 URL 拼接问题,从而实现面向对象编程。
在启动类上添加 @EnableEeignClients 注解:
@EnableFeignClients(basePackages = {"com.extlight.springcloud"}) @EnableEurekaClient @SpringBootApplication public class OrderServerApplication { public static void main(String[] args) { SpringApplication.run(OrderServerApplication.class, args); } }
因为 order-server 项目中引用了 common-api 中的 GoodsServiceClient,不一样属一个项目,为了实例化对象,所以须要在 @EnableFeignClients 注解中添加须要扫描的包路径。
使用 Postman 请求订单系统,请求结果以下图:
请求成功,因为 Feign 封装了 Ribbon,也就实现了负载均衡的功能。