zoukankan      html  css  js  c++  java
  • 负载均衡算法

    负载均衡算法:rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标 , 每次服务重启动后rest 接口计数从1开始

    
    @Component
    public class MyLB implements LoadBalancer {
    
        private AtomicInteger atomicInteger = new AtomicInteger(0);
    
        public final int getAndIncrement(){
            int current;
            int next;
            do{
                current = this.atomicInteger.get();
                next = current >= 2147483647 ? 0 : current + 1;
            }while (!this.atomicInteger.compareAndSet(current,next));
            System.out.println("**************第 "+ next +" 次访问*******");
            //代表第几次访问
            return next;
    
        }
    
    
        //负载均衡算法:rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标 , 每次服务重启动后rest 接口计数从1开始
        @Override
        public ServiceInstance instances(List<ServiceInstance> serviceInstance) {
    
            // serviceInstance.size 获取集群总数
            int index = getAndIncrement() % serviceInstance.size();
            return serviceInstance.get(index);
        }
    }
    
    
    
    
    
    
    public interface LoadBalancer {
    
    
        ServiceInstance instances(List<ServiceInstance> serviceInstance);
    
    }
    
    
    
        @Resource
        private LoadBalancer loadBalancer;
    
        @GetMapping(value = "/consumer/payment/lb")
        public String getPaymentLB()
        {
            List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
            if (instances == null||instances.size() <=0){
                return null;
            }
    
            ServiceInstance serviceInstance = loadBalancer.instances(instances);
            URI uri = serviceInstance.getUri();
    
            return  restTemplate.getForObject(uri+"/payment/lb",String.class);
        }
    
    
    
    
    
    
  • 相关阅读:
    要学习TINY框架要有什么前提条件?
    如何获取最新的代码?
    python 反射的用法
    面试题1
    Process多进程的创建方法
    异常捕捉
    用type动态创建Form
    ModelForm的使用
    git 常见命令
    TVTK库的安装
  • 原文地址:https://www.cnblogs.com/nineberg/p/12604444.html
Copyright © 2011-2022 走看看