Curator的使用
1.依赖导入
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.11</version>
</dependency>
2.连接服务端
1.重连策略
Curator存在RetryPolicy重连策略
RetryForever(int retryIntervalMs)一直重连
RetryOneTime(int sleepMsBetweenRetry)间隔重连
RetryNTimes(int n, int sleepMsBetweenRetries)重连几次
RetryUntilElapsed(int maxElapsedTimeMs, int sleepMsBetweenRetries) 重试直到经过指定的时间
ExponentialBackoffRetry(int baseSleepTimeMs, int maxRetries)随着重试次数增加重试时间间隔变大,指数倍增长baseSleepTimeMs * Math.max(1, random.nextInt(1 << (retryCount + 1)))。
ExponentialBackoffRetry(int baseSleepTimeMs, int maxRetries, int maxSleepMs)
BoundedExponentialBackoffRetry(int baseSleepTimeMs, int maxSleepTimeMs, int maxRetries) baseSleepTimeMs初始sleep时间,maxSleepTimeMs最大sleep时间,maxRetries最大重试次数
2.命名空间
Curator会创建命名空间这个节点后,其他的操作都是就基于命名空间。
package life.xp.distributed.curatordemo;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import java.util.concurrent.CountDownLatch;
/**
* @ClassName: CuratorDemo
* @Description: 基于Curator的zookeeper操作
* @author: XP
* @data: 2020/3/23
*/
public class CuratorDemo {
public static final String zkServerIps = "IP:2181";
public static final String path ="/curator/test";
public static final CountDownLatch countDownLatch=new CountDownLatch(1);
// Curator客户端
public static CuratorFramework client = null;
public static void main(String[] args) throws Exception {
//重试策略 间隔重试时间为1秒 总共5次
RetryPolicy retryPolicy=new ExponentialBackoffRetry(1000, 5);
//实例化客户端(建造者模式)
client=CuratorFrameworkFactory.builder()
//.authorization() 权限访问
.connectString(zkServerIps) // 放入zookeeper服务器ip
.sessionTimeoutMs(10000).retryPolicy(retryPolicy) // 设定会话时间以及重连策略
.namespace("workspace").build(); // 设置命名空间以及开始建立连接
// 启动Curator客户端
client.start();
//查看是否连接
boolean started = client.isStarted();
System.out.println("当前客户端的状态:" + (started ? "连接中..." : "已关闭..."));
byte[] data = "this is a test data".getBytes(); // 节点数据
String result = client.create().creatingParentsIfNeeded() // 创建父节点,也就是会递归创建
.withMode(CreateMode.PERSISTENT) // 节点类型
.withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE) // 节点的acl权限
.forPath(path, data);
System.out.println(result + "节点,创建成功...");
Thread.sleep(1000);
// 关闭客户端
client.close();
// 获取当前客户端的状态
started = client.isStarted();
System.out.println("当前客户端的状态:" + (started ? "连接中..." : "已关闭..."));
}
}