zookeeper curator学习(增删改查)(1)

主要参考的是curator,github地址:https://github.com/apache/curator/tree/master/curator-examples。

zookeeper版本为zookeeper-3.4.9(需要查找合适的curator版本)

源码地址:https://gitee.com/zhangjunqing/spring-boot/tree/master/zookeeper

(1)pom文件如下

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.zookeeper</groupId>
  <artifactId>zookeeper</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>zookeeper</name>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

 <dependencies>
     <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>2.7.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-test</artifactId>
            <version>2.7.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-x-discovery</artifactId>
            <version>2.7.0</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.2</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
            <scope>test</scope>
        </dependency>
 </dependencies>

</project>

(2)使用curator链接zookeeper程序如下:

package com.topsec.framework;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class CreateClientExamples
{

    //创建简单的 CuratorFramework
    public static CuratorFramework createSimple(String connectionString)
    {
        // these are reasonable arguments for the ExponentialBackoffRetry. The first
        // retry will wait 1 second - the second will wait up to 2 seconds - the
        // third will wait up to 4 seconds.
        ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 3);

        // The simplest way to get a CuratorFramework instance. This will use default values.
        // The only required arguments are the connection string and the retry policy
        return CuratorFrameworkFactory.newClient(connectionString, retryPolicy);
    }

    //创建复杂的CuratorFramework
    public static CuratorFramework  createWithOptions(String connectionString, RetryPolicy retryPolicy, int connectionTimeoutMs, int sessionTimeoutMs)
    {
        // using the CuratorFrameworkFactory.builder() gives fine grained control
        // over creation options. See the CuratorFrameworkFactory.Builder javadoc
        // details
        return CuratorFrameworkFactory.builder()
            .connectString(connectionString)
            .retryPolicy(retryPolicy)
            .connectionTimeoutMs(connectionTimeoutMs)
            .sessionTimeoutMs(sessionTimeoutMs)
            // etc. etc.
            .build();
    }
}

(3)进行节点增删改查的示例代码

package com.topsec.framework;

import java.util.List;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorListener;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Watcher;

public class CrudExamples
{
    public static void      create(CuratorFramework client, String path, byte[] payload) throws Exception
    {
        // this will create the given ZNode with the given data
        client.create().forPath(path, payload);
    }

    public static void      createEphemeral(CuratorFramework client, String path, byte[] payload) throws Exception
    {
        // this will create the given EPHEMERAL ZNode with the given data
        client.create().withMode(CreateMode.EPHEMERAL).forPath(path, payload);
    }

    public static String    createEphemeralSequential(CuratorFramework client, String path, byte[] payload) throws Exception
    {
        // this will create the given EPHEMERAL-SEQUENTIAL ZNode with the given data using Curator protection.

        /*
            Protection Mode:
            It turns out there is an edge case that exists when creating sequential-ephemeral nodes. The creation
            can succeed on the server, but the server can crash before the created node name is returned to the
            client. However, the ZK session is still valid so the ephemeral node is not deleted. Thus, there is no
            way for the client to determine what node was created for them.
            Even without sequential-ephemeral, however, the create can succeed on the sever but the client (for various
            reasons) will not know it. Putting the create builder into protection mode works around this. The name of
            the node that is created is prefixed with a GUID. If node creation fails the normal retry mechanism will
            occur. On the retry, the parent path is first searched for a node that has the GUID in it. If that node is
            found, it is assumed to be the lost node that was successfully created on the first try and is returned to
            the caller.
         */
        return client.create().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(path, payload);
    }

    public static void      setData(CuratorFramework client, String path, byte[] payload) throws Exception
    {
        // set data for the given node
        client.setData().forPath(path, payload);
    }

    public static void      setDataAsync(CuratorFramework client, String path, byte[] payload) throws Exception
    {
        // this is one method of getting event/async notifications
        CuratorListener listener = new CuratorListener()
        {
            public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception
            {
                // examine event for details
                System.out.println("返回事件" + event.getWatchedEvent());
            }
        };
        client.getCuratorListenable().addListener(listener);

        // set data for the given node asynchronously. The completion notification
        // is done via the CuratorListener.
        client.setData().inBackground().forPath(path, payload);
    }

    public static void      setDataAsyncWithCallback(CuratorFramework client, BackgroundCallback callback, String path, byte[] payload) throws Exception
    {
        // this is another method of getting notification of an async completion
        client.setData().inBackground(callback).forPath(path, payload);
    }

    public static void      delete(CuratorFramework client, String path) throws Exception
    {
        // delete the given node
        client.delete().forPath(path);
    }

    public static void      guaranteedDelete(CuratorFramework client, String path) throws Exception
    {
        // delete the given node and guarantee that it completes

        /*
            Guaranteed Delete
            Solves this edge case: deleting a node can fail due to connection issues. Further, if the node was
            ephemeral, the node will not get auto-deleted as the session is still valid. This can wreak havoc
            with lock implementations.
            When guaranteed is set, Curator will record failed node deletions and attempt to delete them in the
            background until successful. NOTE: you will still get an exception when the deletion fails. But, you
            can be assured that as long as the CuratorFramework instance is open attempts will be made to delete
            the node.
         */

        client.delete().guaranteed().forPath(path);
    }

    public static List<String> watchedGetChildren(CuratorFramework client, String path) throws Exception
    {
        /**
         * Get children and set a watcher on the node. The watcher notification will come through the
         * CuratorListener (see setDataAsync() above).
         */
        return client.getChildren().watched().forPath(path);
    }

    public static List<String> watchedGetChildren(CuratorFramework client, String path, Watcher watcher) throws Exception
    {
        /**
         * Get children and set the given watcher on the node.
         */
        return client.getChildren().usingWatcher(watcher).forPath(path);
    }
}

(4)测试程序:

package com.topsec.framework;

import org.apache.curator.framework.CuratorFramework;

public class FrameworkTest {
    //zookeeper集群
    public static final String ZOOKEEPERSTRING = "192.168.99.129:2181,192.168.99.153:2181,192.168.99.171:2181";

    public static void main(String args[]) {
        CuratorFramework  curatorFramework = null;
        try {
            curatorFramework = CreateClientExamples.createSimple(ZOOKEEPERSTRING);
            curatorFramework.start();
            //创建节点  只能在存在的节点下创建,并且该节点必须不存在
//            CrudExamples.create(curatorFramework, "/zookeeperTest/number2", "test1".getBytes());

            //创建临时节点
            //CrudExamples.createEphemeral(curatorFramework, "/zookeeperTest/tempNode", "tempNode".getBytes());

            //创建临时顺序节点
            //CrudExamples.createEphemeralSequential(curatorFramework, "/zookeeperTest/tempSeqNode", "tempSeqNode".getBytes());

            //修改节点
            //CrudExamples.setData(curatorFramework, "/zookeeperTest/number2", "number2".getBytes());

            //异步设置数据
            //CrudExamples.setDataAsync(curatorFramework, "/zookeeperTest/number2", "number3".getBytes());

            //删除节点
            //CrudExamples.delete(curatorFramework, "/zookeeperTest/number2");

            //安全保证删除
            CrudExamples.guaranteedDelete(curatorFramework, "/zookeeperTest/number2");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(curatorFramework!=null) {
                curatorFramework.close();
            }
        }

    }
}

补充知识

CuratorFramework提供的方法:

create() 开始创建操作, 可以调用额外的方法(比如方式mode 或者后台执行background) 并在最后调用forPath()指定要操作的ZNode
delete() 开始删除操作. 可以调用额外的方法(版本或者后台处理version or background)并在最后调用forPath()指定要操作的ZNode
checkExists() 开始检查ZNode是否存在的操作. 可以调用额外的方法(监控或者后台处理)并在最后调用forPath()指定要操作的ZNode
getData() 开始获得ZNode节点数据的操作. 可以调用额外的方法(监控、后台处理或者获取状态watch, background or get stat) 并在最后调用forPath()指定要操作的ZNode
setData() 开始设置ZNode节点数据的操作. 可以调用额外的方法(版本或者后台处理) 并在最后调用forPath()指定要操作的ZNode
getChildren() 开始获得ZNode的子节点列表。 以调用额外的方法(监控、后台处理或者获取状态watch, background or get stat) 并在最后调用forPath()指定要操作的ZNode
inTransaction() 开始是原子ZooKeeper事务. 可以复合create, setData, check, and/or delete 等操作然后调用commit()作为一个原子操作提交

事件类型以及事件的方法如下:

Event Type Event Methods
CREATE
getResultCode() and getPath()

DELETE getResultCode() and getPath()
EXISTS getResultCode(), getPath() and getStat()
GETDATA getResultCode(), getPath(), getStat() and getData()
SETDATA getResultCode(), getPath() and getStat()
CHILDREN getResultCode(), getPath(), getStat(), getChildren()
WATCHED getWatchedEvent()
时间: 2025-01-09 20:16:17

zookeeper curator学习(增删改查)(1)的相关文章

zookeeper基本命令,增删改查

zookeeper被广泛的使用,由于项目中用到了dubbo框架,所以今天也来简单分享一下zookeeper的简单命令,来查询服务和节点信息,不说了,直接来增删改查命令. -h命令: [zk: localhost:2189(CONNECTED) 35] h ZooKeeper -server host:port cmd args addauth scheme auth close config [-c] [-w] [-s] connect host:port create [-s] [-e] [-

大数据系列之分布式数据库HBase-1.2.4+Zookeeper 安装及增删改查实践

之前介绍过关于HBase 0.9.8版本的部署及使用,本篇介绍下最新版本HBase1.2.4的部署及使用,有部分区别,详见如下: 1. 环境准备: 1.需要在Hadoop[hadoop-2.7.3] 启动正常情况下安装,hadoop安装可参考LZ的文章 大数据系列之Hadoop分布式集群部署 2. 资料包  zookeeper-3.4.9.tar.gz,hbase-1.2.4-bin.tar.gz 2. 安装步骤: 1.安装zookeeper 1.解压zookeeper-3.4.9.tar.gz

layui 学习增删改查分页(1)

1 layui 经典模块化前端框架 由职业前端倾情打造,面向所有层次的前后端开发者,零门槛开箱即用的前端UI解决方案 2 比较符合 ui设计 美感不好的 同学 3 上手快 扁平化 4正片 首先在GitHub 上 star 然后 下载到本地 记录下自己的 debug 经历 1 加载table // 表格渲染 var tableIns= table.render({ elem: '#dateTable' //指定原始表格元素选择器(推荐id选择器) , height: vipTable.getFul

学习Mysql第二天--增删改查

跬步何以至千里 今天主要学习增删改查,坚持每天学习一点 增删改查主要还是记住命令以及语法. 增删改查命令中都需要有表名 增 insert into 表名 value(); 删 delete from 表明 where from 参数 = “”; 改 update 表名 set 参数 = "" where owner = ""; 查 select * from 表名; 查看数据表的结构 (参数 类型等) desc 表名; mysql数据类型(引用菜鸟教程) MySQL

SSM+dubbo+zookeeper实现基本的增删改查

前言 本文中使用的项目是由上一篇文章中的项目改造而来.具体来说,就是引入了dubbo和zookeeper,并将Controller层与service层dao层进行了拆分,使双方通过service接口远程调用的形式,再次实现了基本的增删改查. 上一篇文章:http://www.cnblogs.com/hanzx/p/10016468.html 名词解释 dubbo:dubbo是阿里开源的一款优秀的java RPC框架,可以配合spring和zookeeper使用.它提供了这些功能:面向接口的远程方

Mysql学习笔记(三)对表数据的增删改查。

写在前面:(一些牢骚,可以直接跳到分割线后) 太过敏感的人不会快乐,不幸的是我正是这种性格的人. 从培训机构毕业后,迫于经济方面的压力,和当时的班里的一个同学住在了一起,我们在一个公司上班.谁知道这都是不开心生活的源头,从每天早晨开始心情就很糟糕.他是个脾气很慢的人,我是个急脾气,特别是在早上上班的时候.由此种种吧,实在是不胜枚举.算了,还是不说了,太痛苦了,我不太喜欢说别人的坏话.我是学心理学的,已经用各种方法去安慰自己,但是都不太奏效. 回想以往和朋友的交往中,我虽然不算十分合群的人,但绝对

Android学习---SQLite数据库的增删改查和事务(transaction)调用

上一篇文章中介绍了手工拼写sql语句进行数据库的CRUD操作,本文将介绍调用sqlite内置的方法实现CRUD操作,其实质也是通过拼写sql语句. 首先,创建一个新的android项目: 其次,查看代码实现增删查改: 1.创建DB工具类 MyDBHelper.java(创建数据库的操作) package com.amos.android_db; import android.content.Context; import android.database.sqlite.SQLiteDatabas

Rhythmk 学习 Hibernate 01 - maven 创建Hibernate 项目之 增删改查入门

1.环境: Maven :3.1.1 开发工具:Spring Tool Suite 数据库 : Mysql  5.6 2.项目文件结构 文件代码: 2.1 .pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.ap

Mybatis学习总结(二)—使用接口实现数据的增删改查

在这一篇中,让我们使用接口来实现一个用户数据的增删改查. 完成后的项目结构如下图所示: 在这里,person代表了一个用户的实体类.在该类中,描述了相关的信息,包括id.name.age.id_num信息.而personMapper则是该实体类的一个配置文件.需要注意的是,在上一篇博文中,namespace属性的值是其本身,而在这一篇中,使用的是接口.那么两者有什么区别呢?使用接口,那么相关的操作方法不用自己去实现,只需要调用该接口的相关的方法就能够实现相应的功能. 那么,在这里就有一个问题,接