基礎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();
}
}