下面2张图来自:http://www.open-open.com/doc/view/2e0a82e0081d489dace301a2c512053c
关于Zookeeper服务安装,配置,启动, 客户端操作参见:
http://aiilive.blog.51cto.com/1925756/1684451
http://aiilive.blog.51cto.com/1925756/1684145
1.利用Zookeeper的znode数据版本生成序列号
利用zkClient封装包操作实现:
//提前创建好存储Seq的"/createSeq"结点 CreateMode.PERSISTENT public static final String SEQ_ZNODE = "/seq" //通过znode数据版本实现分布式seq生成 public static class Task1 implements Runnable { private final String taskName; public Task1(String taskName) { this.taskName = taskName; } @Override public void run() { ZkClient zkClient = new ZkClient("192.168.88.153:2181", 3000, 1000); Stat stat = zkClient.writeData(SEQ_ZNODE, new byte[0], -1); int versionAsSeq = stat.getVersion(); System.out.println(taskName + " obtain seq=" + versionAsSeq); zkClient.close(); } } //main final ExecutorService service = Executors.newFixedThreadPool(20); for (int i = 0; i < 20; i++) { service.execute(new Task1("[Concurrent-" + i + "]")); }
2.利用临时带序列号的znode实现和分布式锁持久化znode实现
2.1 下图是利用分布式锁持久化znode实现
客户端采用apache curator 框架,代码:https://code.csdn.net/snippets/929300
2.2利用临时带序列号的znode实现
客户端采用:zkClient (https://github.com/adyliu/zkclient)
//提前创建好锁对象的结点"/lock" CreateMode.PERSISTENT public static final String LOCK_ZNODE = "/lock";
//分布式锁实现分布式seq生成 public static class Task2 implements Runnable, IZkChildListener { private final String taskName; private final ZkClient zkClient; private final String lockPrefix = "/loc"; private final String selfZnode; public Task2(String taskName) { this.taskName = taskName; zkClient = new ZkClient("192.168.88.153:2181", 30000, 10000); selfZnode = zkClient.createEphemeralSequential(LOCK_ZNODE + lockPrefix, new byte[0]); } @Override public void run() { zkClient.subscribeChildChanges(LOCK_ZNODE, this); do { } while (zkClient.isConnected()); } private void createSeq() { Stat stat = new Stat(); byte[] oldData = zkClient.readData(LOCK_ZNODE, stat); byte[] newData = update(oldData); zkClient.writeData(LOCK_ZNODE, newData); System.out.println(taskName + selfZnode + " obtain seq=" + new String(newData)); } private byte[] update(byte[] currentData) { String s = new String(currentData); int d = Integer.parseInt(s); d = d + 1; s = String.valueOf(d); return s.getBytes(); } @Override public void handleChildChange(String parentPath, List<String> currentChildren) throws Exception { String[] childrensZnode = currentChildren.toArray(new String[currentChildren.size()]); Arrays.sort(childrensZnode); String minZnode = LOCK_ZNODE + "/" + childrensZnode[0]; if (selfZnode.equals(minZnode)) { createSeq(); zkClient.unsubscribeChildChanges(LOCK_ZNODE, this); zkClient.delete(selfZnode); zkClient.close(); } } }
完整代码参见:https://code.csdn.net/snippets/929320
时间: 2024-09-29 11:19:49