简述
spring-cloud-starter-loadbalancer 是 Spring Cloud 中的一个组件,它提供了客户端负载均衡的功能。在 Spring Cloud 的早期版本中,Netflix Ribbon 被广泛用作客户端负载均衡器,但随着时间推移和 Netflix Ribbon 进入维护模式,Spring Cloud 社区开始转向更灵活、更易于维护的替代方案。
spring-cloud-starter-loadbalancer 是基于 Spring 5 的 WebClient 构建的,并使用了 Reactor(Spring 5 的反应式编程模型的核心库)来实现异步非阻塞的负载均衡请求。它与 Spring Cloud 的服务发现和配置结合得非常好,可以很容易地与 Eureka、Consul、Nacos 等服务发现组件一起使用。
当将 spring-cloud-starter-loadbalancer 添加到Spring Boot 应用程序中时,可以使用 WebClient.Builder 的 loadBalancer 方法来创建一个具有负载均衡功能的 WebClient 实例。这个 WebClient 实例会自动从服务发现中获取服务实例列表,并使用内置的负载均衡算法(如轮询、随机等)来选择一个服务实例来发送请求。
例如,如果正在使用 Eureka 作为服务发现,并且想要发送一个 GET 请求到名为 “my-service” 的服务,可以这样做:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
@Service
public class MyServiceClient {
@Autowired
private WebClient.Builder webClientBuilder;
@Bean
@LoadBalanced
public WebClient.Builder loadBalancedWebClientBuilder() {
return WebClient.builder();
}
public String getSomethingFromMyService() {
// 注意这里我们直接使用了 "my-service" 作为 URI,而不是具体的服务实例地址
return webClientBuilder.build()
.get()
.uri("http://my-service/some-endpoint")
.retrieve()
.bodyToMono(String.class)
.block(); // 注意:block() 方法会阻塞当前线程,通常只在非反应式上下文中使用
}
}
主要特点
- 基于 WebClient:与 Spring 5 的 WebClient 紧密集成,提供了反应式(Reactive)的 HTTP 客户端功能。
- 服务发现集成:与 Spring Cloud 的服务发现组件(如 Eureka、Consul、Nacos 等)集成,可以自动获取服务实例列表。
- 内置负载均衡算法:提供了内置的负载均衡算法,如轮询(Round Robin)、随机(Random)等。
- 反应式编程:支持反应式编程模型,允许非阻塞的 I/O 操作和异步处理。
- 灵活性:与 Ribbon 相比,提供了更多的灵活性和扩展性,可以更容易地定制负载均衡行为。
- 与 Spring Cloud Gateway 集成:与 Spring Cloud Gateway 紧密集成,为其提供了负载均衡功能。
使用
- 添加依赖:在 Maven 或 Gradle 项目中添加 spring-cloud-starter-loadbalancer 依赖。
<!-- SpringCloud Loadbalancer -->
<dependency>