SpringCloud2组件之Feign详解
开发环境:
-
开发工具:IntelliJ IDEA Java版本:1.8 Spring Boot版本:2.1.6.RELEASE Spring Cloud版本:Greenwich.SR1
工程简介:
在中,我们使用Ribbon客户端负载均衡实现微服务之间的调用,Ribbon本质上就是一个RestTemplate对象。使用RestTemplate时,除了要编写所调用微服务的URL,还需要包装所调用微服务所返回的结果。为了克服这些不足,Spring Cloud提供了声明式调用组件—Feign。 Feign是一个基于接口的编程方式,开发者只需要声明接口和配置注解,在调度接口方法时,Spring Cloud根据配置来调度对应的REST风格的请求,从其他微服务系统中获取数据。
1、创建Spring Boot工程
中已将server-eureka、client-product、client-user工程搭建完毕,现在我们只需要对client-product微服务进行改造即可。
2、配置client-product微服务
(1)pom.xml中添加Feign依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
(2)client-product目录
(3)application.yml
server: #服务端口 port: 8000 spring: #服务名称 application: name: product eureka: client: service-url: #服务注册地址 defaultZone: http://localhost:9000/eureka/
(4)ClientUserApplication
package com.ming.product; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; @SpringBootApplication @EnableEurekaClient //开启Eureka客户端 @EnableFeignClients //开启Feign客户端 public class ClientProductApplication { public static void main(String[] args) { SpringApplication.run(ClientProductApplication.class, args); } }
(5)FeignService
package com.ming.product.service; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @FeignClient("USER") //开启Feign客户端,USER是client-user微服务的serviceId public interface FeignService { //对应要调用的client-user微服务控制层请求方法 @RequestMapping("/user/{id}") String getUser(@PathVariable("id") Long id); }
(6)ProductController
package com.ming.product.controller; import com.ming.product.service.FeignService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class ProductController { @Autowired private FeignService feignService; @RequestMapping("/feign") public String testRibbon() { String userId = ""; //调用10次用户微服务 for (int i = 1; i <= 10; i++) { //调用定义Feign客户端方法 userId = feignService.getUser((long) i); } return userId; } }
3、测试工程
依次点击ServerEurekaApplication、ClientProductApplication、ClientUserApplication1、ClientUserApplication2,工程都启动成功后。在浏览器地址栏访问 http://localhost:9000,其结果如下:
在浏览器地址栏访问 http://localhost:8000/feign,其结果如下:
查看控制台,其结果如下:
client-product微服务总共调用了10次client-user微服务,开启了2个client-user微服务实例,每个微服务实例被调用了5次。由于Feign客户端负载均衡默认采用轮询机制,根据时间可以看出,先调用ClientUserApplication1实例,后调用ClientUserApplication2实例,再调用ClientUserApplication1实例,又调用ClientUserApplication2实例,依次轮询调用。