介绍下Curator的基本API
- 使用静态工程方法创建会话
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", 5000, 5000, retryPolicy);
RetryPolicy为重试策略 第一个参数为baseSleepTimeMs初始的sleep时间,用于计算之后的每次重试的sleep时间。 第二个参数为maxRetries,最大重试次数
- 使用Fluent风格api创建
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); CuratorFramework client = CuratorFrameworkFactory.builder() .connectString("127.0.0.1:2181") .sessionTimeoutMs(5000) // 会话超时时间 .connectionTimeoutMs(5000) // 连接超时时间 .retryPolicy(retryPolicy) .namespace("base") // 包含隔离名称 .build(); client.start();
- 创建数据节点
lient.create().creatingParentContainersIfNeeded() // 递归创建所需父节点 .withMode(CreateMode.PERSISTENT) // 创建类型为持久节点 .forPath("/nodeA", "init".getBytes()); // 目录及内容
- 删除数据节点
client.delete() .guaranteed() // 强制保证删除 .deletingChildrenIfNeeded() // 递归删除子节点 .withVersion(10086) // 指定删除的版本号 .forPath("/nodeA");
- 读取数据节点
byte[] bytes = client.getData().forPath("/nodeA"); System.out.println(new String(bytes));
- 读stat
Stat stat = new Stat(); client.getData() .storingStatIn(stat) .forPath("/nodeA");
- 修改数据节点
client.setData() .withVersion(10086) // 指定版本修改 .forPath("/nodeA", "data".getBytes());
- 事务
client.inTransaction().check().forPath("/nodeA") .and() .create().withMode(CreateMode.EPHEMERAL).forPath("/nodeB", "init".getBytes()) .and() .create().withMode(CreateMode.EPHEMERAL).forPath("/nodeC", "init".getBytes()) .and() .commit();
- 其他
client.checkExists() // 检查是否存在 .forPath("/nodeA"); client.getChildren().forPath("/nodeA"); // 获取子节点的路径
- 异步回调
Executor executor = Executors.newFixedThreadPool(2); client.create() .creatingParentsIfNeeded() .withMode(CreateMode.EPHEMERAL) .inBackground((curatorFramework, curatorEvent) -> { System.out.println(String.format("eventType:%s,resultCode:%s",curatorEvent.getType(),curatorEvent.getResultCode())); },executor) .forPath("path");
zk分布式实现的代码分析
先说下这个test方法 描述了 获取zk锁的完整流程
再说下 如何通过访问接口的方式的实现
目录结构
初始化zk客户端连接
zk 客户端申请、释放锁实现
实现了 InitializingBean, DisposableBean接口