`

服务器不同权值的分流算法

    博客分类:
  • java
 
阅读更多
/**
** C#实现
** http://www.cnblogs.com/shanyou/archive/2012/11/09/2763272.html
**/

package com;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class LoadBalance {
	// / <summary>
	// / 锁对象
	// / </summary>
	private static Object locker = new Object();

	// / <summary>
	// / 服务器权重列表
	// / </summary>
	private static List<Integer> weightList = new ArrayList<Integer>();

	// / <summary>
	// / 当前索引
	// / </summary>
	private static int currentIndex;

	// / <summary>
	// / 当前权重
	// / </summary>
	private static int currentWeight;

	private static int maxWeight;

	// / <summary>
	// / 最大公约数
	// / </summary>
	private static int gcd;

	private LoadBalance() {
		currentIndex = -1;
		currentWeight = 0;

		// 获取服务器权重列表 从配置文件
		weightList = GetWeightList();
		maxWeight = GetMaxWeight(weightList);
		gcd = GetMaxGCD(weightList);
	}

	private static List<Integer> GetWeightList() {
		List<Integer> list = new ArrayList<Integer>();
		list.add(3);
		list.add(1);
		list.add(1);
		list.add(4);
		list.add(1);
		list.add(7);

		return list;
	}

	public static Integer Start() {
		synchronized (locker) {
			Integer iWeight = RoundRobin();
			if (iWeight != null) {
				return iWeight;
			}
			return weightList.get(0);
		}
	}

	// / <summary>
	// / 获取最大公约数
	// / </summary>
	// / <param name="list">要查找的int集合</param>
	// / <returns>返回集合中所有数的最大公约数</returns>
	private static int GetMaxGCD(List<Integer> list) {
		Collections.sort(list, new WeightCompare());

		int iMinWeight = weightList.get(0);

		int gcd = 1;

		for (int i = 1; i < iMinWeight; i++) {
			boolean isFound = true;
			for (int iWeight : list) {
				if (iWeight % i != 0) {
					isFound = false;
					break;
				}
			}
			if (isFound)
				gcd = i;
		}
		return gcd;
	}

	// / <summary>
	// / 获取服务器权重集合中的最大权重
	// / </summary>
	// / <param name="list"></param>
	// / <returns></returns>
	private static int GetMaxWeight(List<Integer> list) {
		int iMaxWeight = 0;
		for (int i : list) {
			if (iMaxWeight < i) {
				iMaxWeight = i;
			}
		}
		return iMaxWeight;
	}

	private static Integer RoundRobin() {
		while (true) {
			currentIndex = (currentIndex + 1) % weightList.size();
			if (0 == currentIndex) {
				currentWeight = currentWeight - gcd;
				if (0 >= currentWeight) {
					currentWeight = maxWeight;
					if (currentWeight == 0) {
						return null;
					}
				}
			}

			if (weightList.get(currentIndex) >= currentWeight) {
				return weightList.get(currentIndex);
			}
		}
	}

}

class WeightCompare implements Comparator<Integer> {

	@Override
	public int compare(Integer x, Integer y) {
		return x - y;
	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics