Curator API使用
Curator 是操作ZooKeeper的開源客戶端.
類似於JDBC什麼的吧.
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.4.2</version>
</dependency>
同步介面
1.建立節點
節點型別一共有四種
CreateMode.EPHEMERAL 臨時節點
CreateMode.EPHEMERAL_SEQUENTIAL 臨時順序節點
CreateMode.PERSISTENT 持久節點
CreateMode.PERSISTENT_SEQUENTIAL 持久順序節點
2.刪除節點
3.讀取節點資料
4.更新節點資料
非同步介面
1.非同步介面呼叫BackgroundCallback回撥函式
結果:
DELETE
EventCode:-101
pool-1-thread-1
2.事件監聽
監聽節點資料變化.
監聽的節點可以不存在,但是一旦建立也會觸發事件.
刪除監聽的節點,不會觸發事件.
監聽子節點變化
子節點變化包括
event.getType()
CHILD_ADDED 子節點建立
CHILD_UPDATED 子節點資料變更
CHILD_REMOVED 子節點刪除
3.Master選舉
4.分散式鎖
5.分散式計數器
6.分散式Barrier
參考:
類似於JDBC什麼的吧.
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.4.2</version>
</dependency>
同步介面
1.建立節點
- public static void main(String[] args) throws Exception {
- CuratorFramework client = getConnection();
- client.create().forPath("/t1", "t1".getBytes());
- client.create().withMode(CreateMode.EPHEMERAL).forPath("/e1","e1".getBytes());
- client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/p1/p2/p3","p1".getBytes());
- client.close();
- }
- public static CuratorFramework getConnection() {
- CuratorFramework client;
- client = CuratorFrameworkFactory.newClient("172.16.1.78:2181", new ExponentialBackoffRetry(1000, 3));
- client.start();
- return client;
- }
節點型別一共有四種
CreateMode.EPHEMERAL 臨時節點
CreateMode.EPHEMERAL_SEQUENTIAL 臨時順序節點
CreateMode.PERSISTENT 持久節點
CreateMode.PERSISTENT_SEQUENTIAL 持久順序節點
2.刪除節點
- public static void main(String[] args) throws Exception {
- CuratorFramework client = getConnection();
- //遞迴刪除子節點
- client.delete().deletingChildrenIfNeeded().forPath("/p1");
- //強制保證刪除
- client.delete().guaranteed().forPath("/t1");
- client.close();
- }
3.讀取節點資料
- public static void main(String[] args) throws Exception {
- CuratorFramework client = getConnection();
- byte[] data=client.getData().forPath("/t");
- System.out.println(new String(data));
- }
4.更新節點資料
- public static void main(String[] args) throws Exception {
- CuratorFramework client = getConnection();
- client.setData().forPath("/t","Hello World".getBytes());
- client.close();
- }
非同步介面
1.非同步介面呼叫BackgroundCallback回撥函式
- public static void main(String[] args) throws Exception {
- final CountDownLatch latch = new CountDownLatch(1);
- ExecutorService threadpool = Executors.newFixedThreadPool(5);
- BackgroundCallback callback = new BackgroundCallback() {
- public void processResult(CuratorFramework arg0, CuratorEvent event) throws Exception {
- System.out.println(event.getType().name());
- System.out.println("EventCode:" + event.getResultCode());
- System.out.println(Thread.currentThread().getName());
- latch.countDown();
- }
- };
- CuratorFramework client = getConnection();
- client.delete().inBackground(callback, threadpool).forPath("/t");
- latch.await();
- threadpool.shutdown();
- client.close();
- }
結果:
DELETE
EventCode:-101
pool-1-thread-1
監聽節點資料變化.
監聽的節點可以不存在,但是一旦建立也會觸發事件.
刪除監聽的節點,不會觸發事件.
- public static void main(String[] args) throws Exception {
- CuratorFramework client = getConnection();
- final NodeCache cache = new NodeCache(client, "/t");
- cache.start(true);
- cache.getListenable().addListener(new NodeCacheListener() {
- public void nodeChanged() throws Exception {
- byte[] data = cache.getCurrentData().getData();
- System.out.println(new String(data));
- }
- });
- Thread.sleep(Integer.MAX_VALUE);
- }
監聽子節點變化
- public static void main(String[] args) throws Exception {
- CuratorFramework client = getConnection();
- final PathChildrenCache cache = new PathChildrenCache(client, "/t", true);
- cache.start(StartMode.POST_INITIALIZED_EVENT);
- cache.getListenable().addListener(new PathChildrenCacheListener() {
- public void childEvent(CuratorFramework arg0, PathChildrenCacheEvent event) throws Exception {
- System.out.println(event.getType().name());
- System.out.println(event.getData().getPath());
- }
- });
- Thread.sleep(Integer.MAX_VALUE);
- }
子節點變化包括
event.getType()
CHILD_ADDED 子節點建立
CHILD_UPDATED 子節點資料變更
CHILD_REMOVED 子節點刪除
3.Master選舉
- public static void main(String[] args) throws Exception {
- CuratorFramework client = getConnection();
- LeaderSelector selector=new LeaderSelector(client,"/master",new LeaderSelectorListenerAdapter() {
- public void takeLeadership(CuratorFramework client) throws Exception {
- System.out.println("成為Master角色");
- Thread.sleep(1000);
- System.out.println("釋放");
- }
- });
- selector.autoRequeue();
- selector.start();
- Thread.sleep(Integer.MAX_VALUE);
- }
4.分散式鎖
- public static void main(String[] args) throws Exception {
- CuratorFramework client = getConnection();
- final InterProcessMutex lock = new InterProcessMutex(client, "/lock");
- final CountDownLatch latch = new CountDownLatch(1);
- for (int i = 0; i < 30; i++) {
- new Thread(new Runnable() {
- public void run() {
- try {
- latch.await();
- lock.acquire();
- System.out.println(new Date());
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- lock.release();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }).start();
- }
- latch.countDown();
- }
5.分散式計數器
- public static void main(String[] args) throws Exception {
- CuratorFramework client = getConnection();
- DistributedAtomicInteger atomicInteger = new DistributedAtomicInteger(client, "/atomicInteger",
- new RetryNTimes(3, 1000));
- AtomicValue<Integer> rc = atomicInteger.add(8);
- System.out.println(rc.succeeded());
- System.out.println(rc.postValue());
- }
6.分散式Barrier
- public static void main(String[] args) throws Exception {
- final CountDownLatch latch = new CountDownLatch(30);
- for (int i = 0; i < 30; i++) {
- new Thread(new Runnable() {
- public void run() {
- try {
- CuratorFramework client = getConnection();
- DistributedBarrier barrier = new DistributedBarrier(client, "/barrier");
- barrier.setBarrier();
- System.out.println(Thread.currentThread().getName() + ",waiting..");
- latch.countDown();
- barrier.waitOnBarrier();
- System.out.println(Thread.currentThread().getName() + ",start!!");
- client.close();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }).start();
- }
- latch.await();
- CuratorFramework client = getConnection();
- DistributedBarrier barrier = new DistributedBarrier(client, "/barrier");
- barrier.removeBarrier();
- client.close();
- }
參考:
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29254281/viewspace-2097459/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- Apache Curator 操作Zookeeper apiApacheAPI
- Curator(ZoooKeeper客戶端)使用詳解客戶端
- zookeeper 開源客戶端Curator使用客戶端
- Zookeeper之Curator(1)客戶端對節點的一些監控事件的api使用客戶端事件API
- Zookeeper之Curator(1)客戶端基本的建立,刪除,更新,查詢操作api客戶端API
- Curator 重連策略與超時
- 聊一聊 Zookeeper 客戶端之 Curator客戶端
- Zookeeper分散式鎖實現Curator十一問分散式
- ZooKeeper和Curator相關經驗總結
- ZooKeeper 分散式鎖 Curator 原始碼 01:可重入鎖分散式原始碼
- Zookeeper和Curator-Framework實踐系列之: 配置管理Framework
- ElasticSearch Java API使用ElasticsearchJavaAPI
- EasyExcel Java API 使用ExcelJavaAPI
- 4、hdfs api使用API
- ChatGpt聊天API使用ChatGPTAPI
- IntersectionObserver API 使用教程ServerAPI
- ZooKeeper 使用 Java APIJavaAPI
- elasticsearch api client使用ElasticsearchAPIclient
- rocket 原生 API 使用API
- linux使用者api和核心apiLinuxAPI
- 為什麼使用API?什麼情況下避免使用API?API
- 使用ASP.NET Web API構建RESTful APIASP.NETWebAPIREST
- 使用 Java 持久化 APIJava持久化API
- java api使用ElastichSearch指南JavaAPIAST
- 使用 Java API 操作 elasticsearchJavaAPIElasticsearch
- API文件使用方法API
- 使用 Kubernetes APIAPI
- ChatGPT API使用介紹ChatGPTAPI
- Elasticsearch的Bulk API使用ElasticsearchAPI
- socket基本的API使用API
- 將zookeeper curator與springboot專案進行整合(重點)Spring Boot
- Zookeeper和Curator-Framework實踐之:分散式訊息佇列Framework分散式佇列
- 如何使用電商API介面API介面如何應用API
- ZooKeeper 分散式鎖 Curator 原始碼 03:可重入鎖併發加鎖分散式原始碼
- 【API知識】RestTemplate的使用APIREST
- GitLab 相關 API 使用GitlabAPI
- Sentinel GO API 使用指南GoAPI
- laravel 使用路由api.phpLaravel路由APIPHP