---
title: "大规模分布式系统架构与设计实战笔记3"
author: "kfq131"
date: "2014-08-04T15:44:23Z"
tags: []
categories: ["互联网"]
slug: "3"
draft: false
lastmod: "2014-08-04T15:44:23Z"
id: 2100089
url: "https://kfq131.iteye.com/blog/2100089"
---

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

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

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

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

Java代码  [![收藏代码](http://2710067471.iteye.com/images/icon_star.png)]()

01. import com.fourinone.BeanContext;
02. import com.fourinone.ParkLocal;
03. import com.fourinone.ObjectBean;
04. public class GetConfigA
05. {
06. public static void main(String\[] args)
07. {
08. ParkLocal pl=BeanContext.getPark();
09. ObjectBean oldob=null;
10. while(true)
11. {
12. ObjectBean newob=pl.getLastest("zhejiang","hangzhou",oldob);
13. if(newob!=null)
14. {
15. System.out.println(newob);
16. oldob=newob;
17. }
18. }
19. }
20. }

 

Java代码  [![收藏代码](http://2710067471.iteye.com/images/icon_star.png)]()

01. import com.fourinone.BeanContext;
02. import com.fourinone.ParkLocal;
03. import com.fourinone.LastestListener;
04. import com.fourinone.LastestEvent;
05. import com.fourinone.ObjectBean;
06. public class GetConfigB implements LastestListener
07. {
08. public boolean happenLastest(LastestEvent le)
09. {
10. ObjectBean ob = (ObjectBean)le.getSource();
11. System.out.println(ob);
12. return false;
13. }
14. public static void main(String\[] args)
15. {
16. ParkLocal pl = BeanContext.getPark();
17. pl.addLastestListener("zhejiang", "hangzhou", null, new GetConfigB());
18. }
19. }

 

Java代码  [![收藏代码](http://2710067471.iteye.com/images/icon_star.png)]()

01. import com.fourinone.\*;
02. public class SetConfig
03. {
04. public static void main(String\[] args)
05. {
06. ParkLocal pl = BeanContext.getPark();
07. ObjectBean xihu = pl.create("zhejiang", "hangzhou", "xihu",AuthPolicy.OP\_ALL);
08. try{Thread.sleep(8000);}catch(Exception e){}
09. ObjectBean yuhang = pl.update("zhejiang", "hangzhou","xihu");
10. }
11. }

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

同时，fourinone又提供了处理宕机的情况： 

Java代码  [![收藏代码](http://2710067471.iteye.com/images/icon_star.png)]()

01. import com.fourinone.BeanContext;
02. public class ParkMasterSlave
03. {
04. public static void main(String\[] args)
05. {
06. String\[]\[] master = new String\[]\[]{{"localhost","1888"},{"localhost","1889"}};
07. String\[]\[] slave = new String\[]\[]{{"localhost","1889"},{"localhost","1888"}};
08. String\[]\[] server = null;
09. if(args\[0].equals("M"))
10. server = master;
11. else if(args\[0].equals("S"))
12. server = slave;
13. BeanContext.startPark(server\[0]\[0],Integer.parseInt(server\[0]\[1]), server);
14. }
15. }

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