|
| 1 | +package zookeeper.CreateGroup; |
| 2 | + |
| 3 | +import org.apache.zookeeper.*; |
| 4 | + |
| 5 | +import java.io.IOException; |
| 6 | +import java.util.concurrent.CountDownLatch; |
| 7 | + |
| 8 | +/** |
| 9 | + * Created by yaosheng on 2017/1/16. |
| 10 | + */ |
| 11 | + |
| 12 | +public class CreateGroup implements Watcher{ |
| 13 | + |
| 14 | + private static final int SESSION_TIMEOUT = 1000;//会话延时 |
| 15 | + |
| 16 | + private ZooKeeper zk = null; |
| 17 | + |
| 18 | + private CountDownLatch countDownLatch = new CountDownLatch(1);//同步计数器 |
| 19 | + |
| 20 | + |
| 21 | + /** |
| 22 | + * 这里我们使用了同步计数器CountDownLatch,在connect方法中创建执行了zk = new ZooKeeper(hosts, SESSION_TIMEOUT, this);之后, |
| 23 | + * 下边接着调用了CountDownLatch对象的await方法阻塞,因为这是zk客户端不一定已经完成了与服务端的连接,在客户端连接到服务端时会触发观察者调用process()方法, |
| 24 | + * 我们在方法里边判断一下触发事件的类型,完成连接后计数器减一,connect方法中解除阻塞。 |
| 25 | + 还有两个地方需要注意:这里创建的znode的访问权限是open的,且该znode是持久化存储的。 |
| 26 | + * |
| 27 | + */ |
| 28 | + @Override |
| 29 | + public void process(WatchedEvent event) { |
| 30 | + if(event.getState() == Event.KeeperState.SyncConnected){ |
| 31 | + countDownLatch.countDown();//计数器减一 |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + /** |
| 36 | + * 创建zk对象 |
| 37 | + * 当客户端连接上zookeeper时会执行process(event)里的countDownLatch.countDown(),计数器的值变为0,则countDownLatch.await()方法返回。 |
| 38 | + * @param hosts |
| 39 | + * @throws IOException |
| 40 | + * @throws InterruptedException |
| 41 | + */ |
| 42 | + public void connect(String hosts) throws IOException, InterruptedException { |
| 43 | + zk = new ZooKeeper(hosts, SESSION_TIMEOUT, this); |
| 44 | + countDownLatch.await();//阻塞程序继续执行 |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * 创建group |
| 49 | + * |
| 50 | + * @param groupName 组名 |
| 51 | + * @throws KeeperException |
| 52 | + * @throws InterruptedException |
| 53 | + */ |
| 54 | + public void create(String groupName) throws KeeperException, InterruptedException { |
| 55 | + String path = "/" + groupName; |
| 56 | + String createPath = zk.create(path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE/*允许任何客户端对该znode进行读写*/, CreateMode.PERSISTENT/*持久化的znode*/); |
| 57 | + System.out.println("Created " + createPath); |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * 关闭zk |
| 62 | + * @throws InterruptedException |
| 63 | + */ |
| 64 | + public void close() throws InterruptedException { |
| 65 | + if(zk != null){ |
| 66 | + try { |
| 67 | + zk.close(); |
| 68 | + } catch (InterruptedException e) { |
| 69 | + throw e; |
| 70 | + }finally{ |
| 71 | + zk = null; |
| 72 | + System.gc(); |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + public static void main(String[] args){ |
| 78 | + |
| 79 | + } |
| 80 | +} |
0 commit comments