下面2张图来自:http://www.open-open.com/doc/view/2e0a82e0081d489dace301a2c512053c
关于Zookeeper服务安装,配置,启动,客户端操作参见:
http://www.jb51.cc/article/p-czczykuq-kn.html
http://www.jb51.cc/article/p-atkufdff-kn.html
1.利用Zookeeper的znode数据版本生成序列号
利用zkClient封装包操作实现:
//提前创建好存储Seq的"/createSeq"结点CreateMode.PERSISTENT publicstaticfinalStringSEQ_ZNODE="/seq" //通过znode数据版本实现分布式seq生成 publicstaticclassTask1implementsRunnable{ privatefinalStringtaskName; publicTask1(StringtaskName){ this.taskName=taskName; } @Override publicvoidrun(){ ZkClientzkClient=newZkClient("192.168.88.153:2181",3000,1000); Statstat=zkClient.writeData(SEQ_ZNODE,newbyte[0],-1); intversionAsSeq=stat.getVersion(); System.out.println(taskName+"obtainseq="+versionAsSeq); zkClient.close(); } } //main finalExecutorServiceservice=Executors.newFixedThreadPool(20); for(inti=0;i<20;i++){ service.execute(newTask1("[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 publicstaticfinalStringLOCK_ZNODE="/lock";
//分布式锁实现分布式seq生成 publicstaticclassTask2implementsRunnable,IZkChildListener{ privatefinalStringtaskName; privatefinalZkClientzkClient; privatefinalStringlockPrefix="/loc"; privatefinalStringselfZnode; publicTask2(StringtaskName){ this.taskName=taskName; zkClient=newZkClient("192.168.88.153:2181",30000,10000); selfZnode=zkClient.createEphemeralSequential(LOCK_ZNODE+lockPrefix,newbyte[0]); } @Override publicvoidrun(){ zkClient.subscribeChildChanges(LOCK_ZNODE,this); do{ }while(zkClient.isConnected()); } privatevoidcreateSeq(){ Statstat=newStat(); byte[]oldData=zkClient.readData(LOCK_ZNODE,stat); byte[]newData=update(oldData); zkClient.writeData(LOCK_ZNODE,newData); System.out.println(taskName+selfZnode+"obtainseq="+newString(newData)); } privatebyte[]update(byte[]currentData){ Strings=newString(currentData); intd=Integer.parseInt(s); d=d+1; s=String.valueOf(d); returns.getBytes(); } @Override publicvoidhandleChildChange(StringparentPath,List<String>currentChildren)throwsException{ String[]childrensZnode=currentChildren.toArray(newString[currentChildren.size()]); Arrays.sort(childrensZnode); StringminZnode=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
本文出自 “野马红尘” 博客,请务必保留此出处http://www.jb51.cc/article/p-stsiyghh-kn.html