SpringCloud之Ribbon訪問策略(七)

Git源碼: https://github.com/chenhang666/SpringCloud

1、Ribbon自帶的策略及使用方法

直接new對應的策略即可

2、自定義策略

在消費端的主啓動類加載自定義Ribbon配置類


根據GitHub上源碼(RandomRule源碼)修改策略

public class RandomRule_ZY extends AbstractLoadBalancerRule
{

	// total = 0 // 當total==5以後,我們指針才能往下走,
	// index = 0 // 當前對外提供服務的服務器地址,
	// total需要重新置爲零,但是已經達到過一個5次,我們的index = 1
	// 分析:我們5次,但是微服務只有8001 8002 8003 三臺
	// 
	
	
	private int total = 0; 			// 總共被調用的次數,目前要求每臺被調用5次
	private int currentIndex = 0;	// 當前提供服務的機器號

	public Server choose(ILoadBalancer lb, Object key)
	{
		if (lb == null) {
			return null;
		}
		Server server = null;

		while (server == null) {
			if (Thread.interrupted()) {
				return null;
			}
			List<Server> upList = lb.getReachableServers();
			List<Server> allList = lb.getAllServers();

			int serverCount = allList.size();
			if (serverCount == 0) {
				/*
				 * No servers. End regardless of pass, because subsequent passes only get more
				 * restrictive.
				 */
				return null;
			}

//			int index = rand.nextInt(serverCount);// java.util.Random().nextInt(3);
//			server = upList.get(index);

			
//			private int total = 0; 			// 總共被調用的次數,目前要求每臺被調用5次
//			private int currentIndex = 0;	// 當前提供服務的機器號
            if(total < 5)
            {
	            server = upList.get(currentIndex);
	            total++;
            }else {
	            total = 0;
	            currentIndex++;
	            if(currentIndex >= upList.size())
	            {
	              currentIndex = 0;
	            }
            }			
			
			
			if (server == null) {
				/*
				 * The only time this should happen is if the server list were somehow trimmed.
				 * This is a transient condition. Retry after yielding.
				 */
				Thread.yield();
				continue;
			}

			if (server.isAlive()) {
				return (server);
			}

			// Shouldn't actually happen.. but must be transient or a bug.
			server = null;
			Thread.yield();
		}

		return server;

	}

	@Override
	public Server choose(Object key)
	{
		return choose(getLoadBalancer(), key);
	}

	@Override
	public void initWithNiwsConfig(IClientConfig clientConfig)
	{
		// TODO Auto-generated method stub

	}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章