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

1.1 导入jar包


    
    org.springframework.cloud
    spring-cloud-starter-loadbalancer

1.2 屏蔽ribbon

spring
  cloud:
    loadbalancer:
      ribbon:
        enabled: false
  1. 3 添加注解(同Ribbon)
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
    return new RestTemplate();
}

1.4 调用(同Ribbon)

@RestController
public class UsersController {

    //服务提供者名称
    private static final String REMOTE_URL = "http://SEARCH";

    @Autowired
    private  RestTemplate 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 {

    @Bean
    ReactorLoadBalancer 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
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

}

2.3其它不变,重新测试即可

你可能感兴趣的:(Java基础知识,spring,cloud,java,spring)