项目源码:https://download.csdn.net/download/weixin_42950079/87150709
Spring Cloud Nacos 2021 移除了 Ribbon,在Spring Cloud Commons 项目中添加了 Spring Cloud LoadBalancer 作为新的负载均衡器
<dependency>
<groupId>com.alibaba.cloudgroupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
<version>2021.0.1.0version>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-loadbalancerartifactId>
dependency>
LoadBalancer 的负载均衡策略没有 Ribbon 那么丰富,只提供了RandomLoadBalancer
、NacosLoadBalancer
、RoundRobinLoadBalancer
,在不指定的时候默认使用RoundRobinLoadBalancer
轮询负载均衡策略。 👉👉👉推荐使用整合 Ribbon 的方式来实现负载均衡。
ReactorLoadBalancer
@Configuration
public class CustomLoadBalancerConfiguration {
// 参考 NacosLoadBalancerClientConfiguration
@Bean
public ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment, LoadBalancerClientFactory loadBalancerClientFactory) {
String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
return new RandomLoadBalancer(loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
}
}
ReactorLoadBalancer
@Configuration
public class CustomLoadBalancerConfiguration {
// 参考 NacosLoadBalancerClientConfiguration
@Bean
public ReactorLoadBalancer<ServiceInstance> roundRobinLoadBalancer(Environment environment, LoadBalancerClientFactory loadBalancerClientFactory) {
String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
return new RoundRobinLoadBalancer(loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
}
}
@SpringBootApplication
@LoadBalancerClients(
@LoadBalancerClient(value = "stock-service", configuration = CustomLoadBalancerConfiguration.class)
)
public class Order8010Application {
public static void main(String[] args) {
SpringApplication.run(Order8010Application.class);
System.out.println("order8010 --> 项目启动成功");
}
}
测试时,记得先启动 Nacos 集群哦,然后再浏览器中输入:localhost:8010/order/add