Spring Cloud Loadbalancer

Spring Cloud Loadbalancer---客户端负载均衡器springcloud 2020.0.1 版本之后 删除了eureka中的ribbon,替代ribbon的是spring cloud自带的LoadBalancer,但公司开发中并没有那么快更新,大部分项目还是在用Ribbon , 但未来可能会改用Spring Cloud Loadbalancer 。我们一起来看一下Spring Cloud Loadbalancer的使用
一Spring Cloud Loadbalancer和RestTemplate相结合实现负载均衡整体使用方法同Ribbon
【Spring Cloud Loadbalancer】1.1 导入jar包
<dependency><!-- Spring Cloud loadbalancer 负载均衡--><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-loadbalancer</artifactId></dependency>1.2 屏蔽ribbon
springcloud:loadbalancer:ribbon:enabled: false

  1. 3 添加注解(同Ribbon)
@Bean@LoadBalancedpublic RestTemplate restTemplate(){return new RestTemplate();}1.4 调用(同Ribbon)
@RestControllerpublic class UsersController {//服务提供者名称private static final String REMOTE_URL = "http://SEARCH";@AutowiredprivateRestTemplate restTemplate;@GetMapping("goods")public ResponseResult searchGoods(){return restTemplate.getForObject(REMOTE_URL+"/goods",ResponseResult.class);}}二 修改负载均衡方式2.1 创建一个配置类
package com.test.eureka.config;import org.springframework.cloud.client.ServiceInstance;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.core.env.Environment;//这里 不需要 @configuration注解重要的事情说三遍public class CustomLoadBalancerConfiguration {@BeanReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment,LoadBalancerClientFactory loadBalancerClientFactory) {String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);//这里是返回随机负载均衡方式return new RandomLoadBalancer(loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class),name);}}2.2 添加注解
在@LoadBalanced注解所在类上添加注解
@LoadBalancerClient(name = "SEARCH",configuration = CustomLoadBalancerConfiguration.class)@Configuration//注意这里的name属性 需要和eureka页面中的服务提供者名字一直 此时页面中是大写@LoadBalancerClient(name = "SEARCH",configuration = CustomLoadBalancerConfiguration.class)public class RemoteClientConfiguration {@Bean@LoadBalancedpublic RestTemplate restTemplate(){return new RestTemplate();}}2.3其它不变 , 重新测试即可

    推荐阅读