依然饭跑跑 发表于 2017-4-19 10:45:01

(转)使用ZooKeeper实现的两个实例

           我们来看看,利用ZK实现分布式锁和实现实时更新server列表的功能的例子,转自:
                       http://coolxing.iteye.com/blog/1871630
                       http://coolxing.iteye.com/blog/1871520
  **************************************以下为转载********************************
  分布式锁:
场景描述
     在分布式应用, 往往存在多个进程提供同一服务. 这些进程有可能在相同的机器上, 也有可能分布在不同的机器上. 如果这些进程共享了一些资源, 可能就需要分布式锁来锁定对这些资源的访问.
本文将介绍如何利用zookeeper实现分布式锁.
思路
    进程需要访问共享数据时, 就在"/locks"节点下创建一个sequence类型的子节点, 称为thisPath. 当thisPath在所有子节点中最小时, 说明该进程获得了锁. 进程获得锁之后, 就可以访问共享资源了. 访问完成后, 需要将thisPath删除. 锁由新的最小的子节点获得.
有了清晰的思路之后, 还需要补充一些细节. 进程如何知道thisPath是所有子节点中最小的呢? 可以在创建的时候, 通过getChildren方法获取子节点列表, 然后在列表中找到排名比thisPath前1位的节点, 称为waitPath, 然后在waitPath上注册监听, 当waitPath被删除后, 进程获得通知, 此时说明该进程获得了锁.
实现
以一个DistributedClient对象模拟一个进程的形式, 演示zookeeper分布式锁的实现.
 


[*]public class DistributedClient {  
[*]    // 超时时间  
[*]    private static final int SESSION_TIMEOUT = 5000;  
[*]    // zookeeper server列表  
[*]    private String hosts = "localhost:4180,localhost:4181,localhost:4182";  
[*]    private String groupNode = "locks";  
[*]    private String subNode = "sub";  
[*]  
[*]    private ZooKeeper zk;  
[*]    // 当前client创建的子节点  
[*]    private String thisPath;  
[*]    // 当前client等待的子节点  
[*]    private String waitPath;  
[*]  
[*]    private CountDownLatch latch = new CountDownLatch(1);  
[*]  
[*]    /** 
[*]     * 连接zookeeper 
[*]     */  
[*]    public void connectZookeeper() throws Exception {  
[*]        zk = new ZooKeeper(hosts, SESSION_TIMEOUT, new Watcher() {  
[*]            public void process(WatchedEvent event) {  
[*]                try {  
[*]                    // 连接建立时, 打开latch, 唤醒wait在该latch上的线程  
[*]                    if (event.getState() == KeeperState.SyncConnected) {  
[*]                        latch.countDown();  
[*]                    }  
[*]  
[*]                    // 发生了waitPath的删除事件  
[*]                    if (event.getType() == EventType.NodeDeleted && event.getPath().equals(waitPath)) {  
[*]                        doSomething();  
[*]                    }  
[*]                } catch (Exception e) {  
[*]                    e.printStackTrace();  
[*]                }  
[*]            }  
[*]        });  
[*]  
[*]        // 等待连接建立  
[*]        latch.await();  
[*]  
[*]        // 创建子节点  
[*]        thisPath = zk.create("/" + groupNode + "/" + subNode, null, Ids.OPEN_ACL_UNSAFE,  
[*]                CreateMode.EPHEMERAL_SEQUENTIAL);  
[*]  
[*]        // wait一小会, 让结果更清晰一些  
[*]        Thread.sleep(10);  
[*]  
[*]        // 注意, 没有必要监听"/locks"的子节点的变化情况  
[*]        List<String> childrenNodes = zk.getChildren("/" + groupNode, false);  
[*]  
[*]        // 列表中只有一个子节点, 那肯定就是thisPath, 说明client获得锁  
[*]        if (childrenNodes.size() == 1) {  
[*]            doSomething();  
[*]        } else {  
[*]            String thisNode = thisPath.substring(("/" + groupNode + "/").length());  
[*]            // 排序  
[*]            Collections.sort(childrenNodes);  
[*]            int index = childrenNodes.indexOf(thisNode);  
[*]            if (index == -1) {  
[*]                // never happened  
[*]            } else if (index == 0) {  
[*]                // inddx == 0, 说明thisNode在列表中最小, 当前client获得锁  
[*]                doSomething();  
[*]            } else {  
[*]                // 获得排名比thisPath前1位的节点  
[*]                this.waitPath = "/" + groupNode + "/" + childrenNodes.get(index - 1);  
[*]                // 在waitPath上注册监听器, 当waitPath被删除时, zookeeper会回调监听器的process方法  
[*]                zk.getData(waitPath, true, new Stat());  
[*]            }  
[*]        }  
[*]    }  
[*]  
[*]    private void doSomething() throws Exception {  
[*]        try {  
[*]            System.out.println("gain lock: " + thisPath);  
[*]            Thread.sleep(2000);  
[*]            // do something  
[*]        } finally {  
[*]            System.out.println("finished: " + thisPath);  
[*]            // 将thisPath删除, 监听thisPath的client将获得通知  
[*]            // 相当于释放锁  
[*]            zk.delete(this.thisPath, -1);  
[*]        }  
[*]    }  
[*]  
[*]    public static void main(String[] args) throws Exception {  
[*]        for (int i = 0; i < 10; i++) {  
[*]            new Thread() {  
[*]                public void run() {  
[*]                    try {  
[*]                        DistributedClient dl = new DistributedClient();  
[*]                        dl.connectZookeeper();  
[*]                    } catch (Exception e) {  
[*]                        e.printStackTrace();  
[*]                    }  
[*]                }  
[*]            }.start();  
[*]        }  
[*]  
[*]        Thread.sleep(Long.MAX_VALUE);  
[*]    }  
[*]}   

思考
       思维缜密的朋友可能会想到, 上述的方案并不安全. 假设某个client在获得锁之前挂掉了, 由于client创建的节点是ephemeral类型的, 因此这个节点也会被删除, 从而导致排在这个client之后的client提前获得了锁. 此时会存在多个client同时访问共享资源.
对上面的解释:
    现在有subs5 sub6  subs7  subs8几个子节点,当前subs5正获得锁,如果subs6对应的client6挂掉,则subs6被删除--出发了client7那边的监听,导致client7也拿到了锁,导致5和7的客户端同时得到锁。
   如何解决这个问题呢? 可以在接到waitPath的删除通知的时候, 进行一次确认, 确认当前的thisPath是否真的是列表中最小的节点.
 


[*]// 发生了waitPath的删除事件  
[*]if (event.getType() == EventType.NodeDeleted && event.getPath().equals(waitPath)) {  
[*]    // 确认thisPath是否真的是列表中的最小节点  
[*]    List<String> childrenNodes = zk.getChildren("/" + groupNode, false);  
[*]    String thisNode = thisPath.substring(("/" + groupNode + "/").length());  
[*]    // 排序  
[*]    Collections.sort(childrenNodes);  
[*]    int index = childrenNodes.indexOf(thisNode);  
[*]    if (index == 0) {  
[*]        // 确实是最小节点  
[*]        doSomething();  
[*]    } else {  
[*]        // 说明waitPath是由于出现异常而挂掉的  
[*]        // 更新waitPath  
[*]        waitPath = "/" + groupNode + "/" + childrenNodes.get(index - 1);  
[*]        // 重新注册监听, 并判断此时waitPath是否已删除  
[*]        if (zk.exists(waitPath, true) == null) {  
[*]            doSomething();  
[*]        }  
[*]    }  
[*]}  

    另外, 由于thisPath和waitPath这2个成员变量会在多个线程中访问, 最好将他们声明为volatile, 以防止出现线程可见性问题.
另一种思路
   下面介绍一种更简单, 但是不怎么推荐的解决方案.
     每个client在getChildren的时候, 注册监听子节点的变化. 当子节点的变化通知到来时, 再一次通过getChildren获取子节点列表, 判断thisPath是否是列表中的最小节点, 如果是, 则执行资源访问逻辑.
 


[*]public class DistributedClient2 {  
[*]    // 超时时间  
[*]    private static final int SESSION_TIMEOUT = 5000;  
[*]    // zookeeper server列表  
[*]    private String hosts = "localhost:4180,localhost:4181,localhost:4182";  
[*]    private String groupNode = "locks";  
[*]    private String subNode = "sub";  
[*]  
[*]    private ZooKeeper zk;  
[*]    // 当前client创建的子节点  
[*]    private volatile String thisPath;  
[*]  
[*]    private CountDownLatch latch = new CountDownLatch(1);  
[*]  
[*]    /** 
[*]     * 连接zookeeper 
[*]     */  
[*]    public void connectZookeeper() throws Exception {  
[*]        zk = new ZooKeeper(hosts, SESSION_TIMEOUT, new Watcher() {  
[*]            public void process(WatchedEvent event) {  
[*]                try {  
[*]                    // 连接建立时, 打开latch, 唤醒wait在该latch上的线程  
[*]                    if (event.getState() == KeeperState.SyncConnected) {  
[*]                        latch.countDown();  
[*]                    }  
[*]  
[*]                    // 子节点发生变化  
[*]                    if (event.getType() == EventType.NodeChildrenChanged && event.getPath().equals("/" + groupNode)) {  
[*]                        // thisPath是否是列表中的最小节点  
[*]                        List<String> childrenNodes = zk.getChildren("/" + groupNode, true);  
[*]                        String thisNode = thisPath.substring(("/" + groupNode + "/").length());  
[*]                        // 排序  
[*]                        Collections.sort(childrenNodes);  
[*]                        if (childrenNodes.indexOf(thisNode) == 0) {  
[*]                            doSomething();  
[*]                        }  
[*]                    }  
[*]                } catch (Exception e) {  
[*]                    e.printStackTrace();  
[*]                }  
[*]            }  
[*]        });  
[*]  
[*]        // 等待连接建立  
[*]        latch.await();  
[*]  
[*]        // 创建子节点  
[*]        thisPath = zk.create("/" + groupNode + "/" + subNode, null, Ids.OPEN_ACL_UNSAFE,  
[*]                CreateMode.EPHEMERAL_SEQUENTIAL);  
[*]  
[*]        // wait一小会, 让结果更清晰一些  
[*]        Thread.sleep(10);  
[*]  
[*]        // 监听子节点的变化  
[*]        List<String> childrenNodes = zk.getChildren("/" + groupNode, true);  
[*]  
[*]        // 列表中只有一个子节点, 那肯定就是thisPath, 说明client获得锁  
[*]        if (childrenNodes.size() == 1) {  
[*]            doSomething();  
[*]        }  
[*]    }  
[*]  
[*]    /** 
[*]     * 共享资源的访问逻辑写在这个方法中 
[*]     */  
[*]    private void doSomething() throws Exception {  
[*]        try {  
[*]            System.out.println("gain lock: " + thisPath);  
[*]            Thread.sleep(2000);  
[*]            // do something  
[*]        } finally {  
[*]            System.out.println("finished: " + thisPath);  
[*]            // 将thisPath删除, 监听thisPath的client将获得通知  
[*]            // 相当于释放锁  
[*]            zk.delete(this.thisPath, -1);  
[*]        }  
[*]    }  
[*]  
[*]    public static void main(String[] args) throws Exception {  
[*]        for (int i = 0; i < 10; i++) {  
[*]            new Thread() {  
[*]                public void run() {  
[*]                    try {  
[*]                        DistributedClient2 dl = new DistributedClient2();  
[*]                        dl.connectZookeeper();  
[*]                    } catch (Exception e) {  
[*]                        e.printStackTrace();  
[*]                    }  
[*]                }  
[*]            }.start();  
[*]        }  
[*]  
[*]        Thread.sleep(Long.MAX_VALUE);  
[*]    }  
[*]}  

      为什么不推荐这个方案呢? 是因为每次子节点的增加和删除都要广播给所有client, client数量不多时还看不出问题. 如果存在很多client, 那么就可能导致广播风暴--过多的广播通知阻塞了网络. 使用第一个方案, 会使得通知的数量大大下降. 当然第一个方案更复杂一些, 复杂的方案同时也意味着更容易引进bug.
 
***************************************************************************************************
 
实时更新server列表:
    通过之前的3篇博文, 讲述了ZooKeeper的基础知识点. 可以看出, ZooKeeper提供的核心功能是非常简单, 且易于学习的. 可能会给人留下ZooKeeper并不强大的印象, 事实并非如此, 基于ZooKeeper的核心功能, 我们可以扩展出很多非常有意思的应用. 接下来的几篇博文, 将陆续介绍ZooKeeper的典型应用场景.
场景描述
    在分布式应用中, 我们经常同时启动多个server, 调用方(client)选择其中之一发起请求.
    分布式应用必须考虑高可用性和可扩展性: server的应用进程可能会崩溃, 或者server本身也可能会宕机. 当server不够时, 也有可能增加server的数量. 总而言之, server列表并非一成不变, 而是一直处于动态的增减中.
    那么client如何才能实时的更新server列表呢? 解决的方案很多, 本文将讲述利用ZooKeeper的解决方案.
思路
    启动server时, 在zookeeper的某个znode(假设为/sgroup)下创建一个子节点. 所创建的子节点的类型应该为ephemeral, 这样一来, 如果server进程崩溃, 或者server宕机, 与zookeeper连接的session就结束了, 那么其所创建的子节点会被zookeeper自动删除. 当崩溃的server恢复后, 或者新增server时, 同样需要在/sgroup节点下创建新的子节点.
    对于client, 只需注册/sgroup子节点的监听, 当/sgroup下的子节点增加或减少时, zookeeper会通知client, 此时client更新server列表.
实现AppServer
    AppServer的逻辑非常简单, 只须在启动时, 在zookeeper的"/sgroup"节点下新增一个子节点即可.
 


[*]public class AppServer {  
[*]    private String groupNode = "sgroup";  
[*]    private String subNode = "sub";  
[*]  
[*]    /** 
[*]     * 连接zookeeper 
[*]     * @param address server的地址 
[*]     */  
[*]    public void connectZookeeper(String address) throws Exception {  
[*]        ZooKeeper zk = new ZooKeeper("localhost:4180,localhost:4181,localhost:4182", 5000, new Watcher() {  
[*]            public void process(WatchedEvent event) {  
[*]                // 不做处理  
[*]            }  
[*]        });  
[*]        // 在"/sgroup"下创建子节点  
[*]        // 子节点的类型设置为EPHEMERAL_SEQUENTIAL, 表明这是一个临时节点, 且在子节点的名称后面加上一串数字后缀  
[*]        // 将server的地址数据关联到新创建的子节点上  
[*]        String createdPath = zk.create("/" + groupNode + "/" + subNode, address.getBytes("utf-8"),   
[*]            Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);  
[*]        System.out.println("create: " + createdPath);  
[*]    }  
[*]      
[*]    /** 
[*]     * server的工作逻辑写在这个方法中 
[*]     * 此处不做任何处理, 只让server sleep 
[*]     */  
[*]    public void handle() throws InterruptedException {  
[*]        Thread.sleep(Long.MAX_VALUE);  
[*]    }  
[*]      
[*]    public static void main(String[] args) throws Exception {  
[*]        // 在参数中指定server的地址  
[*]        if (args.length == 0) {  
[*]            System.err.println("The first argument must be server address");  
[*]            System.exit(1);  
[*]        }  
[*]          
[*]        AppServer as = new AppServer();  
[*]        as.connectZookeeper(args[0]);  
[*]          
[*]        as.handle();  
[*]    }  
[*]}  

将其打成appserver.jar后待用, 生成jar时别忘了指定入口函数. 具体的教程请自行搜索.
 
实现AppClient
    AppClient的逻辑比AppServer稍微复杂一些, 需要监听"/sgroup"下子节点的变化事件, 当事件发生时, 需要更新server列表.
    注册监听"/sgroup"下子节点的变化事件, 可在getChildren方法中完成. 当zookeeper回调监听器的process方法时, 判断该事件是否是"/sgroup"下子节点的变化事件, 如果是, 则调用更新逻辑, 并再次注册该事件的监听.
 


[*]public class AppClient {  
[*]    private String groupNode = "sgroup";  
[*]    private ZooKeeper zk;  
[*]    private Stat stat = new Stat();  
[*]    private volatile List<String> serverList;  
[*]  
[*]    /** 
[*]     * 连接zookeeper 
[*]     */  
[*]    public void connectZookeeper() throws Exception {  
[*]        zk = new ZooKeeper("localhost:4180,localhost:4181,localhost:4182", 5000, new Watcher() {  
[*]            public void process(WatchedEvent event) {  
[*]                // 如果发生了"/sgroup"节点下的子节点变化事件, 更新server列表, 并重新注册监听  
[*]                if (event.getType() == EventType.NodeChildrenChanged   
[*]                    && ("/" + groupNode).equals(event.getPath())) {  
[*]                    try {  
[*]                        updateServerList();  
[*]                    } catch (Exception e) {  
[*]                        e.printStackTrace();  
[*]                    }  
[*]                }  
[*]            }  
[*]        });  
[*]  
[*]        updateServerList();  
[*]    }  
[*]  
[*]    /** 
[*]     * 更新server列表 
[*]     */  
[*]    private void updateServerList() throws Exception {  
[*]        List<String> newServerList = new ArrayList<String>();  
[*]  
[*]        // 获取并监听groupNode的子节点变化  
[*]        // watch参数为true, 表示监听子节点变化事件.   
[*]        // 每次都需要重新注册监听, 因为一次注册, 只能监听一次事件, 如果还想继续保持监听, 必须重新注册  
[*]        List<String> subList = zk.getChildren("/" + groupNode, true);  
[*]        for (String subNode : subList) {  
[*]            // 获取每个子节点下关联的server地址  
[*]            byte[] data = zk.getData("/" + groupNode + "/" + subNode, false, stat);  
[*]            newServerList.add(new String(data, "utf-8"));  
[*]        }  
[*]  
[*]        // 替换server列表  
[*]        serverList = newServerList;  
[*]  
[*]        System.out.println("server list updated: " + serverList);  
[*]    }  
[*]  
[*]    /** 
[*]     * client的工作逻辑写在这个方法中 
[*]     * 此处不做任何处理, 只让client sleep 
[*]     */  
[*]    public void handle() throws InterruptedException {  
[*]        Thread.sleep(Long.MAX_VALUE);  
[*]    }  
[*]  
[*]    public static void main(String[] args) throws Exception {  
[*]        AppClient ac = new AppClient();  
[*]        ac.connectZookeeper();  
[*]  
[*]        ac.handle();  
[*]    }  
[*]}  

将其打包成appclient.jar后待用, 别忘了指定入口函数.
 
运行
    在运行jar包之前, 需要确认zookeeper中是否已经存在"/sgroup"节点了, 没有不存在, 则创建该节点. 如果存在, 最好先将其删除, 然后再重新创建. ZooKeeper的相关命令可参考我的另一篇博文.
运行appclient.jar: java -jar appclient.jar 开启多个命令行窗口, 每个窗口运行appserver.jar进程:java -jar appserver.jar server0000. "server0000"表示server的地址, 别忘了给每个server设定一个不同的地址. 观察appclient的输出.
依次结束appserver的进程, 观察appclient的输出.
appclient的输出类似于:
 


[*]server list updated: []  
[*]server list updated:   
[*]server list updated:   
[*]server list updated:   
[*]server list updated:   
[*]server list updated:   
[*]server list updated:   
[*]server list updated:   
[*]server list updated: []  
页: [1]
查看完整版本: (转)使用ZooKeeper实现的两个实例