基础API:
@Slf4j
public class CuratorBase {
//zk服务地址
static final String zk_path = "x.x.x.x:2181";
//会话超时
static final int session_timeout=5000;
/**
* 创建客户端
* @return
*/
private static CuratorFramework createClient(){
//重连策略:1秒3次
RetryPolicy retryPolicy = new RetryNTimes(1000,3);
CuratorFramework zkClient = CuratorFrameworkFactory.builder()
.sessionTimeoutMs(session_timeout)
.connectString(zk_path)
.retryPolicy(retryPolicy)
.build();
//开启链接
zkClient.start();
return zkClient;
}
public static void baseAPI() throws Exception {
CuratorFramework zkCli = createClient();
CuratorFrameworkState state = zkCli.getState();
if(state.equals(CuratorFrameworkState.STARTED)){
/**
* 创建节点
*
* zk节点类型:
* PERSISTENT : 持久化节点
* PERSISTENT_SEQUENTIAL : 持久化有序节点
* EPHEMERAL : 会话节点(伴随会话结束消失)
* EPHEMERAL_SEQUENTIAL : 会话有序节点
*/
String path = zkCli.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.PERSISTENT)
.forPath("/curator/base/1", "curator_zkCli:test1".getBytes());
log.info("path : {}",path);
/**
* 获取节点数据
*/
byte[] bytes = zkCli.getData().forPath(path);
log.info("节点数据 : {} ",new String(bytes));
/**
* 更新节点数据
*/
zkCli.setData().forPath(path,"curator_zkCli:test2".getBytes());
byte[] bytes1 = zkCli.getData().forPath(path);
log.info("更新节点数据 : {}",new String(bytes1));
/**
* 获取子节点
*/
List<String> children_paths = zkCli.getChildren().forPath(path);
children_paths.forEach(x->{
log.info(path+" 子节点:"+x);
});
/**
* 检查节点状态
*/
Stat stat = zkCli.checkExists().forPath(path);
log.info(path+" 节点状态:"+stat.toString());
/**
* 删除节点
*/
zkCli.delete().guaranteed().deletingChildrenIfNeeded().forPath(path);
/**
*
*/
ExecutorService executorService = Executors.newCachedThreadPool();
String path2 = zkCli.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.PERSISTENT)
.inBackground(new BackgroundCallback() {
@Override
public void processResult(CuratorFramework curatorFramework, CuratorEvent curatorEvent) throws Exception {
log.info("code:" + curatorEvent.getResultCode());
log.info("type:" + curatorEvent.getType());
log.info("线程为:" + Thread.currentThread().getName());
}
}, executorService)
.forPath("/curator/base/2","curator_zkCli:test3".getBytes());
if(path2!=null){
byte[] bytes2 = zkCli.getData().forPath(path2);
log.info("/curator/base/2 : "+ new String(bytes));
}
}
}
public static void main(String[] args) throws Exception {
baseAPI();
}
}
分布式锁:
/**
* Curator框架实现分布式锁
*/
public class ZkCuratorLock1 {
private static final String zk_server = "x.x.x.x:2181";
private static final String zk_path = "curator/zklock";
public static void doWithLock(CuratorFramework curatorFramework){
List<String> zkPaths = new ArrayList<String>();
zkPaths.add(zk_path);
InterProcessMultiLock lock = new InterProcessMultiLock(curatorFramework,zkPaths);
// InterProcessMutex lock2 = new InterProcessMutex(curatorFramework,zk_path);
try {
if(lock.acquire(30, TimeUnit.SECONDS)){
long threadId = Thread.currentThread().getId();
System.out.println("线程-"+threadId+",acquire lock");
Thread.sleep(1000);
System.out.println("线程-"+threadId+",replease lock");
}
}catch (Exception e){
e.fillInStackTrace();
}finally {
try {
lock.release();
} catch (Exception e) {
e.fillInStackTrace();
}
}
}
public static void main(String[] args) {
ExecutorService es = Executors.newFixedThreadPool(10);
for(int i=10;i>0;i--){
es.execute(new Runnable() {
public void run() {
RetryNTimes retryNTimes = new RetryNTimes(1000, 3);
CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(zk_server, retryNTimes);
curatorFramework.start();
ZkCuratorLock1.doWithLock(curatorFramework);
}
});
}
es.shutdown();
}
}