当前位置 : 主页 > 编程语言 > java >

加权随机数,用于负载均衡

来源:互联网 收集:自由互联 发布时间:2021-06-28
加权随机数 public class WeightRandom { public static Map servers = new HashMap (); static{ servers.put("192.168.20.101", 1); servers.put("192.168.20.102", 2); servers.put("192.168.20.103", 3); servers.put("192.168.20.104", 4); } public
加权随机数
public class WeightRandom {  
      
    public static Map
 
   servers = new HashMap
  
   (); static{ servers.put("192.168.20.101", 1); servers.put("192.168.20.102", 2); servers.put("192.168.20.103", 3); servers.put("192.168.20.104", 4); } public static String selectServer(Map
   
     servers){ if(servers == null || servers.size() == 0) return null; Integer sum = 0; Set
    
     > entrySet = servers.entrySet(); Iterator
     
      > iterator = entrySet.iterator(); while(iterator.hasNext()){ sum += iterator.next().getValue(); } Integer rand = new Random().nextInt(sum) + 1; for(Map.Entry
      
        entry : entrySet){ rand -= entry.getValue(); if(rand <=0){ return entry.getKey(); } } return null; } public static void main(String[] args){ Map
       
         map = new HashMap
        
         (); String key = null; for(int i = 0; i < 1000; i++){ key = selectServer(servers); if(map.containsKey(key)){ map.put(key, map.get(key) + 1); }else{ map.put(key, 1); } } for(String key1 : map.keySet()){ System.out.println(key1 + " " + map.get(key1)); } } }
        
       
      
     
    
   
  
 
上一篇:恢复的收费
下一篇:类目-递归算法
网友评论