当前位置:主页 > 软件编程 > JAVA代码 >

Java加权负载均衡策略实现过程解析

时间:2020-11-12 08:58:10 | 栏目:JAVA代码 | 点击:

加权轮询

后端集群每台机器都分配一个权重,权重高得会承担更多的流量,相反权重低的分配的流量也会少,这种策略允许后端集群机器配置差异化

java实现

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Controller;

@Controller
public class IpMapController extends LogBaseController implements Runnable {
  private static Integer pos = 0;

  // 待scp的Ip列表,Key代表Ip,Value代表该Ip的权重
  public static HashMap<String, Integer> serverWeightMap = new HashMap<String, Integer>();

  static {
  	serverWeightMap.put("127.0.0.1", 1);
  	serverWeightMap.put("127.0.0.2", 1);
  	serverWeightMap.put("127.0.0.3", 1);
  	serverWeightMap.put("127.0.0.4", 1);
  }

  public void run() {
  	// 重建一个Map,避免服务器的上下线导致的并发问题
  	Map<String, Integer> serverMap = new HashMap<String, Integer>();
  	serverMap.putAll(serverWeightMap);

  	// 取得Ip地址List
  	Set<String> keySet = serverMap.keySet();
  	Iterator<String> iterator = keySet.iterator();

  	// 根据权重组成iplist
  	List<String> serverList = new ArrayList<String>();
  	while (iterator.hasNext()) {
  		String server = iterator.next();
  		int weight = serverMap.get(server);
  		for (int i = 0; i < weight; i++)
  			serverList.add(server);
  	}

  	String server = null;
  	synchronized (pos) {
  		if (pos >= keySet.size()){
  			pos = 0;
  		}
  			
  		server = serverList.get(pos);
  		System.out.println("server:" + server + ",pos=" + pos);
  		pos++;
  	}
  	
  }

  public static void main(String[] args) {
  	 IpMapController ipRunnable = new IpMapController();

  	for (int i = 0; i <= 10; i++) {
  		System.out.println("t" + i);
  		new Thread(ipRunnable).start();
  	}
  }
}

多线程输出结果

t0
t1
t2
t3
t4
t5
t6
server:127.0.0.4,pos=0
server:127.0.0.3,pos=1
server:127.0.0.2,pos=2
server:127.0.0.2,pos=2
t7
server:127.0.0.4,pos=0
server:127.0.0.3,pos=1
t8
server:127.0.0.2,pos=2
server:127.0.0.2,pos=2
t9
server:127.0.0.4,pos=0
t10
server:127.0.0.3,pos=1
server:127.0.0.2,pos=2

您可能感兴趣的文章:

相关文章