1.Curator框架入门代码
这是构建curator的client连接zookeeper集群的构建
//path地址String pathName = "/user/dir";RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);CuratorFramework client = CuratorFrameworkFactory//指定zookeeper集群的host:<port>.newClient("192.168.3.36:2181,192.168.3.37:2181,192.168.3.24:2181",retryPolicy);client.start();//判断pathName是否创建if (client.checkExists().forPath(pathName)!= null){System.out.println(String.format("------ THis is: %s",new String(client.getData().forPath(pathName))));}else {client.create().creatingParentsIfNeeded().forPath(pathName, "hello wallacefw".getBytes());System.out.println(new String(client.getData().forPath(pathName)));}
2.Curator关于重入锁分析及理解
关于重入锁的代码如下:
//重入锁构建InterProcessMutex lock = new InterProcessMutex(client, "/locks/lock_01");//获取锁lock.acquire();Thread.sleep(1000);//释放锁lock.release();
3对2的步骤细节分析
在执行InterProcessMutex lock = new InterProcessMutex(client, "/locks/lock_01")代码时候,创建InterProcessMutex的
zookeeper分布式锁对象
private static final String LOCK_NAME = "lock-";//这里创建了 InterProcessMutex 对象,且对public InterProcessMutex(CuratorFramework client, String path){this(client, path, LOCK_NAME, 1, new StandardLockInternalsDriver());}InterProcessMutex(CuratorFramework client, String path, String lockName, int maxLeases, LockInternalsDriver driver){basePath = path;internals = new LockInternals(client, driver, path, lockName, maxLeases);}
- 这时候会对Zookeeper全局同步一个分布式锁的空间,命名为
/locks/lock_01
