上一篇中介绍了 Ribbon 的基本使用,将来使用 Ribbon 调用服务,下面讲解如何使用 Feign 调用服务,并配置负载均衡策略。
Spring Cloud Feign 基于 Netflix Feign 实现的,整理 Spring Cloud Ribbon 与 Spring Cloud Hystrix,默认实现了负载均衡功能,并且实现了声明式的伪Http客户端,Feign 是基于接口的注解开发。
启动 eureka-service,再启动三次 spring-demo-service ,端口分别为 8281、8282、8283。访问 localhost:8761,如下
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
org.springframework.cloud
spring-cloud-starter-openfeign
org.springframework.boot
spring-boot-starter-web
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class ServiceFeignApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceFeignApplication.class, args);
}
}
在启动类中,通过 @EnableEurekaClient 向 eureka server 注册,通过 @EnableFeignClients 注解开启 Feign 的功能。
@FeignClient(value = "spring-demo-service")
public interface SpringDemoFeignService {
@RequestMapping(value = "port", method = RequestMethod.GET)
String hello();
}
通过 @FeignClient 指定调用的服务。@RequestMapping 的 value 值和 spring-demo-service 提供的服务接口的 @RequestMapping 的 value 值一致。
@RestController
public class SpringDemoFeignController {
@Autowired
SpringDemoFeignService springDemoFeignService;
@RequestMapping(value = "hello", method = RequestMethod.GET)
public String port() {
return springDemoFeignService.hello();
}
}
通过 Feign 客户端 SpringDemoFeignService 调用服务。
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8382
spring:
application:
name: 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 的服务实例调用是随机调用,而不再是之前的轮流调用,说明负载均衡策略配置成功。