SpringCloud之----LoadBalancer客户端负载均衡工具

时间:2024-6-20    作者:老大夫    分类: SpringCloud


平替不再更新的Ribbon

它有多种实现类

Spring RestTemplate as a LoadBalancer Client

Spring RestClient as a LoadBalancer Client

Spring WebClient as a LoadBalancer Client

Spring WebFlux WebClient with ReactorLoadBalancerExchangeFilterFunction

常用RestTemplate

使用loadbalancer轮巡模式

  1. 客户模块添加依赖
<!--loadbalancer-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
  1. 配置类一定要添加注解@loadbalancer

  1. 使用Template远程调用服务模块
@GetMapping("/pay/get/info")
    public String getInfoByConsul(){
        return restTemplate.getForObject(PaymentSrv_URL+"/pay/get/info",String.class);
    }

更换切换算法(默认是轮巡)

@Configuration
@LoadBalancerClient(
        //下面的value值大小写一定要和consul里面的名字一样,必须一样
        value = "cloud-payment-service",configuration = RestTemplateConfig.class)
public class RestTemplateConfig
{
    @Bean
    @LoadBalanced //使用@LoadBalanced注解赋予RestTemplate负载均衡的能力
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    @Bean
    ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment,
                                                            LoadBalancerClientFactory loadBalancerClientFactory) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);

        return new RandomLoadBalancer(loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
    }
}


扫描二维码,在手机上阅读

推荐阅读: