SpringCloud-负载均衡Ribbon

  一、配置使用

       1、添加依赖(该依赖包含在eureka-client依赖中

<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
 </dependency>

        2、在RestTemplate上添加@LoadBalanced注解

@Configuration
public class ApplicationContextConfig {
     @Bean
     @LoadBalanced
    public RestTemplate getRestTemplate(){
         return new RestTemplate();
     }
}
  二、IRule替换负载策略

        以随机为例

        1、添加配置类(注意不要放到@ComponentScan所能扫描到的包下

@Configuration
public class MyStyleRule {
     @Bean
    public IRule myRule(){
         /**
          * 定义为随机
          */
         return new RandomRule();
     }
}

       2、在启动类上添加注解

              @RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MyStyleRule.class)

             name:为服务注册名称

             configuration:为策略类

      3、自定义实现轮询策略

          声明接口

public interface LoadBalancer {
     ServiceInstance instances(List<ServiceInstance> serviceInstances);
}

         实现接口

@Component
public class MyLb implements LoadBalancer
{
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getAndIncremant(){
        int current;
        int next;
        do{
            current = this.atomicInteger.get();
            //Integer.MAX_VALUE=2147483647
            next = current >= Integer.MAX_VALUE ? 0 : current +1 ;
        }while(!this.atomicInteger.compareAndSet(current,next));
        return next;
    };

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int index = getAndIncremant() % serviceInstances.size();
        return serviceInstances.get(index);
    }
}

       测试代码

    @Resource
     private RestTemplate restTemplate;

    @Resource
    private LoadBalancer loadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/consumer/payment/lb")
    public String getPaymentLB(){
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if(instances == null || instances.size() <= 0){
            return null;
        }else{
            ServiceInstance serviceInstance = loadBalancer.instances(instances);
            URI uri = serviceInstance.getUri();
            return restTemplate.getForObject(uri+"/payment/lb",String.class);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值