上一篇中介绍了 Ribbon 的基本使用,将来使用 Ribbon 调用服务,下面讲解如何使用 Feign 调用服务,并配置负载均衡策略。
(一)简介
Spring Cloud Feign 基于 Netflix Feign 实现的,整理 Spring Cloud Ribbon 与 Spring Cloud Hystrix,默认实现了负载均衡功能,并且实现了声明式的伪Http客户端,Feign 是基于接口的注解开发。
(二)搭建服务环境
1. 仍然是基于上一篇的工程
启动 eureka-service,再启动三次 spring-demo-service ,端口分别为 8281、8282、8283。访问 localhost:8761,如下
2. 创建一个module(spring-demo-service-feign),创建过程参考上一篇
3. 添加 pom 依赖
-
<dependency>
-
<groupId>org.springframework.cloud
</groupId>
-
<artifactId>spring-cloud-starter-netflix-eureka-client
</artifactId>
-
</dependency>
-
<dependency>
-
<groupId>org.springframework.cloud
</groupId>
-
<artifactId>spring-cloud-starter-openfeign
</artifactId>
-
</dependency>
-
<dependency>
-
<groupId>org.springframework.boot
</groupId>
-
<artifactId>spring-boot-starter-web
</artifactId>
-
</dependency>
4. 启动类
-
@SpringBootApplication
-
@EnableEurekaClient
-
@EnableFeignClients
-
public
class ServiceFeignApplication {
-
-
public static void main(String[] args) {
-
SpringApplication.run(ServiceFeignApplication.class, args);
-
}
-
}
在启动类中,通过 @EnableEurekaClient 向 eureka server 注册,通过 @EnableFeignClients 注解开启 Feign 的功能。
5. 创建 Feign 接口 SpringDemoFeignService
-
@FeignClient(value =
"spring-demo-service")
-
public
interface SpringDemoFeignService {
-
-
@RequestMapping(value =
"port", method = RequestMethod.GET)
-
String hello();
-
}
通过 @FeignClient 指定调用的服务。@RequestMapping 的 value 值和 spring-demo-service 提供的服务接口的 @RequestMapping 的 value 值一致。
6. 创建 SpringDemoFeignController
-
@RestController
-
public
class SpringDemoFeignController {
-
-
@Autowired
-
SpringDemoFeignService springDemoFeignService;
-
-
@RequestMapping(value =
"hello", method = RequestMethod.GET)
-
public String port() {
-
return springDemoFeignService.hello();
-
}
-
}
通过 Feign 客户端 SpringDemoFeignService 调用服务。
7. 配置文件 application.yaml
eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/ server: port: 8382 spring: application: name: spring-demo-service-feign
8. 启动 spring-demo-service-feign
在浏览器中多次访问 localhost:8382/hello,浏览器会轮流显示如下:
说明 Feign 的负载均衡功能也已实现。
(三)配置负载均衡策略
修改配置文件如下:
eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/ server: port: 8382 spring: application: name: spring-demo-service-feign # Ribbon 的负载均衡策略 spring-demo-service: ribbon: NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
重新启动 spring-demo-service-feign 服务,在浏览器中多次访问 localhost:8382/hello,此时,对 spring-demo-service 的服务实例调用是随机调用,而不再是之前的轮流调用,说明负载均衡策略配置成功。