首页 > 其他分享 >Spring Cloud LoadBalancer

Spring Cloud LoadBalancer

时间:2024-06-03 14:56:47浏览次数:24  
标签:负载 return Spring LoadBalancer 均衡 Cloud

Spring Cloud Alibaba

Spring Cloud LoadBalancer

具体介绍转载:Spring Cloud LoadBalancer 负载均衡策略与缓存机制-CSDN博客

1.依赖

因为 Ribbon 作为早期的客户端负载均衡工具,在 Spring Cloud 2020.0.0 版本之后已经被移除了,取而代之的是 Spring Cloud LoadBalancer,而且 Ribbon 也已经不再维护,所以它也是 Spring 官方推荐的负载均衡解决方案。

其他一些原因:

  1. 更好的兼容性:LoadBalancer就像一个全新的配件,它与Spring Cloud的其他组件搭配得更好。
  2. 支持响应式编程:现在编程界有一种新的编程方式叫做“响应式编程”,LoadBalancer能很好地支持这种现代编程风格。
  3. 易于使用和维护:LoadBalancer的设计易于拼装和修改,这对于开发者来说,维护和定制起来更加方便。
  4. 多功能:LoadBalancer有很多内置功能,比如自动帮你挑选服务器,就像购物网站帮你推荐商品一样聪明。
  <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-loadbalancer</artifactId>
        </dependency>

2.主要配置类

@Configuration
// 在这里配置我们自定义的LoadBalancer策略,注:这里的类为注入Bean的类,而非负载均衡的实现类
@LoadBalancerClients(defaultConfiguration = {NacosSameClusterConfiguration.class})
public class SpringBeanConfiguration {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

}

public class NacosSameClusterConfiguration {
    @Resource
    NacosDiscoveryProperties nacosDiscoveryProperties;

    // 团队开发同ip优先

    @Bean
    public ReactorLoadBalancer<ServiceInstance> customSpringCloudLoadBalancer(Environment environment, LoadBalancerClientFactory loadBalancerClientFactory) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        // 返回自定义或者其他自身的负载均衡算法
        return new CustomSpringCloudLoadBalancer(name,
                loadBalancerClientFactory.getLazyProvider(name,
                        ServiceInstanceListSupplier.class));
    }
}

3.自定义负载均衡

Spring Cloud LoadBalance 自带两种负载均衡算法:

RandomLoadBalancer随机,RoundRobinLoadBalancer轮询(默认)

Spring Cloud Alibaba 负载均衡算法:

NacosLoadBalancer权重

自定义适合团队开发根据自身ip地址负载均衡的算法:

/**
 * 自定义 SpringCloud 负载均衡算法
 *
 */
@Slf4j
@AllArgsConstructor
public class CustomSpringCloudLoadBalancer implements ReactorServiceInstanceLoadBalancer {

    private final String serviceId;

    private final ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider;

    @Override
    public Mono<Response<ServiceInstance>> choose(Request request) {
        ServiceInstanceListSupplier supplier = serviceInstanceListSupplierProvider.getIfAvailable(NoopServiceInstanceListSupplier::new);
        return supplier.get(request).next().map(serviceInstances -> processInstanceResponse(supplier, serviceInstances));
    }

    private Response<ServiceInstance> processInstanceResponse(ServiceInstanceListSupplier supplier,
                                                              List<ServiceInstance> serviceInstances) {
        Response<ServiceInstance> serviceInstanceResponse = getInstanceResponse(serviceInstances);
        if (supplier instanceof SelectedInstanceCallback && serviceInstanceResponse.hasServer()) {
            ((SelectedInstanceCallback) supplier).selectedServiceInstance(serviceInstanceResponse.getServer());
        }
        return serviceInstanceResponse;
    }

    private Response<ServiceInstance> getInstanceResponse(List<ServiceInstance> instances) {
        if (instances.isEmpty()) {
            if (log.isWarnEnabled()) {
                log.warn("No servers available for service: " + serviceId);
            }
            return new EmptyResponse();
        }
        for (ServiceInstance instance : instances) {
            if (NetUtil.localIpv4s().contains(instance.getHost())) {
                return new DefaultResponse(instance);
            }
        }
        return new DefaultResponse(instances.get(ThreadLocalRandom.current().nextInt(instances.size())));
    }

}

4.验证

新建三个系统模块,由基础模块调用系统模块

image-20240603143850496

标签:负载,return,Spring,LoadBalancer,均衡,Cloud
From: https://www.cnblogs.com/hinata/p/18228889

相关文章