一、Spring Cloud LoadBalancer介绍
Spring Cloud LoadBalancer
是Spring Cloud官
网提供的一个客户端负载均衡器,功能类似于Ribbon
。在Spring Cloud Nacos 2021
移除了中Ribbon
组件,Spring Cloud
在Spring Cloud Commons
项目中,添加了Spring Cloud Loadbalancer
作为新的负载均衡器。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-loadbalancer</artifactId>
</dependency>
二、LoadBalancer负载均衡策略
LoadBalancer
的负载均衡策略没有 Ribbon
那么丰富,只提供了RandomLoadBalancer
、NacosLoadBalancer
、RoundRobinLoadBalancer
,在不指定的时候默认使用RoundRobinLoadBalancer
轮询负载均衡策略,此三种策略都是对接口ReactiveLoadBalancer
进行实现。
- RandomLoadBalancer :基于随机访问的负载均衡策略
- NacosLoadBalancer:基于Nacos权重的负载均衡策略
- RoundRobinLoadBalancer:基于轮询的负载均衡策略
三、切换LoadBalancer负载均衡策略
参考:
https://docs.spring.io/spring-cloud-commons/docs/current/reference/html/#rest-template-loadbalancer-client
https://docs.spring.io/spring-cloud-commons/docs/current/reference/html/#custom-loadbalancer-configuration
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClients;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
@Configuration
@LoadBalancerClients(defaultConfiguration = CustomRandomLoadBalancerConfiguration.class)
public class CustomRandomLoadBalancerConfiguration {
@Bean
ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment,
LoadBalancerClientFactory loadBalancerClientFactory) {
String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
return new RandomLoadBalancer(loadBalancerClientFactory
.getLazyProvider(name, ServiceInstanceListSupplier.class),
name);
}
}