大规模分布式系统架构与设计实战笔记3

千峰老师的《大规模分布式系统架构与设计实战》的第三章讲的是分布式协调的实现,在工头-职介所-工人的模型中,分布式协调实际上就是职介所相关的一些内容,包括领导(职介所)怎么产生的,当前领导宕机了怎么办,领导如何管理各个员工(工人)等等一系列问题。

在fourinone中,选取领导并不像paxos算法一样实行基于抢占的少数服从多数的策略,而是一种谦让的策略,相当领导的人在发出当领导的申请之前先问问别人想不想当领导,如果想,他自己就先忍着,如果没有其他人他才出头。这样就避免了冲突。

当领导确定后,有领导统一发号施令,同步各个机器。

而领导又是如何同步各个机器的呢?fourinone框架通过park进行配置信息管理,park提供创建和修改信息的方法,并支持轮训和监听两种方式获取变化的对象,进步保持分布式系统的配置的一致性。

import com.fourinone.BeanContext;
import com.fourinone.ParkLocal;
import com.fourinone.ObjectBean;

public class GetConfigA
{
	public static void main(String[] args)
	{
        ParkLocal pl=BeanContext.getPark();
		ObjectBean oldob=null;
		while(true)
		{
			ObjectBean newob=pl.getLastest("zhejiang","hangzhou",oldob);
			if(newob!=null)
			{
				System.out.println(newob);
				oldob=newob;
			}
		}
	}
}

import com.fourinone.BeanContext;
import com.fourinone.ParkLocal;
import com.fourinone.LastestListener;
import com.fourinone.LastestEvent;
import com.fourinone.ObjectBean;

public class GetConfigB implements LastestListener
{
	public boolean happenLastest(LastestEvent le)
	{
		ObjectBean ob = (ObjectBean)le.getSource();
		System.out.println(ob);
		return false;
	}
	
	public static void main(String[] args)
	{
		ParkLocal pl = BeanContext.getPark();
		pl.addLastestListener("zhejiang", "hangzhou", null, new GetConfigB());
	}
}

import com.fourinone.*;

public class SetConfig
{
	public static void main(String[] args)
	{
		ParkLocal pl = BeanContext.getPark();
		ObjectBean xihu = pl.create("zhejiang", "hangzhou", "xihu",AuthPolicy.OP_ALL);
		try{Thread.sleep(8000);}catch(Exception e){}
		ObjectBean yuhang = pl.update("zhejiang", "hangzhou","xihu");
		
	
	}
}

可以看到,应用程序只需要在ParkLocal中做改动,其他的机器就会感知这种变化进而使整个分布式系统保持一致。

同时,fourinone又提供了处理宕机的情况:
import com.fourinone.BeanContext;

public class ParkMasterSlave
{
	public static void main(String[] args)
	{
		String[][] master = new String[][]{{"localhost","1888"},{"localhost","1889"}};
		String[][] slave = new String[][]{{"localhost","1889"},{"localhost","1888"}};
		
		String[][] server = null;
		if(args[0].equals("M"))
			server = master;
		else if(args[0].equals("S"))
			server = slave;
		
		BeanContext.startPark(server[0][0],Integer.parseInt(server[0][1]), server);
	}
}

只需要启动一个领导和多个备用领导就可以了,当领导宕机就会有备用的领导顶上去。

猜你喜欢

转载自yizhenn.iteye.com/blog/2099995