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);
        }
    
    
    
    
    
    
  • 相关阅读:
    HttpRuntime.Cache的使用经验
    js 字符串中取得第一个字符和最后一个字符
    CSAPP笔记-第一章
    共和党减税法案的个人减税
    bash学习进行中
    建站日志
    Python学习进行中
    Check your data! 数据预处理血泪教训
    bash
    【python技巧系列】在循环中处理异常并继续运行
  • 原文地址:https://www.cnblogs.com/nineberg/p/12604444.html
Copyright © 2011-2022 走看看