zookeeper curator客户端之增删改查

zookeeper curator客户端之增删改查

zookeeper安装:https://www.cnblogs.com/zwcry/p/10272506.html

curator客户端是Apache对zookeeper原生API的封装,在原生API的基础上又支持了每次的事件监听、重试机制、递归等操作。

客户端增删改查测试类:

package com.qy.learn.zk.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 七脉
 * 描述:zookeeper教程相关代码,并非封装,而是测试学习加注释说明,教你使用。实际工作中按照公司开发的代码规范走
 *       apache 的Curator是封装后的客户端,本人不建议自己封装, 可以使用Curator再次封装。
 */
public class MyCuratorClient {
    private static final Logger log = LoggerFactory.getLogger(MyCuratorClient.class);
    
    //集群节点
    public static final String zkServerClusterConnect = "192.168.159.129:2181,192.168.159.129:2182,192.168.159.129:2183";
    
    //单一节点
    public static final String zkServerSingleConnect = "192.168.159.129:2181";
    
    public static void main(String[] args) throws Exception {
        
        CuratorFramework client = client();
        log.info("客户端状态:{}", client.getState());
        
        client.start();
        log.info("客户端状态:{}", client.getState());
        
        
        //创建节点
        //create(client, "/father/me", "me");
        
        //查询节点
        //query(client, "/father/me");
        
        //修改节点的值
        //update(client, "/father/me", "newMe");
        
        //删除节点
        //delete(client, "/father/me");
        
        client.close();
        log.info("客户端状态:{}", client.getState());
    }
    
    /**
     * @author 七脉
     * 描述:获取CuratorFramework的客户端
     * @return
     */
    public static CuratorFramework client(){
        log.info("准备创建CuratorFramework客户端");
        int sessionTimeoutMs = 10000;//会话超时时间
        int connectionTimeoutMs = 3000;//初次链接超时时间
        int n = 3;//重试链接次数
        int sleepMsBetweenRetries = 3000;//每次重试连接间隔毫秒数
        
        //RetryPolicy重试显现策略有很多,具体可以查看RetryPolicy的每个实现类进行测试。
        RetryPolicy retryPolicy = new RetryNTimes(n, sleepMsBetweenRetries);
        
        //CuratorFrameworkFactory.newClient是创建客户端的一种方法
        //CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(zkServerClusterConnect, sessionTimeoutMs, connectionTimeoutMs, retryPolicy);
        
        //创建客户端方法还有 CuratorFrameworkFactory.builder()....
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder().connectString(zkServerClusterConnect).connectionTimeoutMs(connectionTimeoutMs).sessionTimeoutMs(sessionTimeoutMs).retryPolicy(retryPolicy).namespace("myspace").build();
        log.info("完成创建CuratorFramework客户端");
        return curatorFramework;
    }
    
    /**
     * @author 七脉
     * 描述:递归创建节点数据
     * @param client
     * @param path
     * @param data
     * @throws Exception
     */
    public static void create(CuratorFramework client, String path, String data) throws Exception{
        log.info("准备递归创建节点,path:{},data:{}", path, data);
        client.create().creatingParentsIfNeeded()//如果path父节点不存在,一并创建
        .withMode(CreateMode.PERSISTENT)//永久节点
        .withACL(Ids.OPEN_ACL_UNSAFE)//所有可见权限
        .forPath(path, data.getBytes());//设置节点数据
        log.info("完成递归创建节点,path:{},data:{}", path, data);
    }
    
    /**
     * @author 七脉
     * 描述:查询节点值
     * @param client
     * @param path
     * @return
     * @throws Exception
     */
    public static String query(CuratorFramework client, String path) throws Exception{
        log.info("准备查询节点:{} 值",path);
        String data = new String(client.getData().storingStatIn(getStat(client, path)).forPath(path));
        log.info("完成查询节点:{}, 值:{}", path, data);
        return data;
    }
    
    /**
     * @author 七脉
     * 描述:修改节点的值
     * @param client
     * @param path
     * @param data
     * @return
     * @throws Exception
     */
    public static Stat update(CuratorFramework client, String path, String data) throws Exception{
        log.info("准备修改节点:{},值:{}", path, data);
        Stat stat = client.setData().withVersion(getStat(client, path).getVersion()).forPath(path, data.getBytes());
        log.info("完成修改节点:{},值:{}", path, data);
        return stat;
    }
    
    /**
     * @author 七脉
     * 描述:淡出节点
     * @param client
     * @param path
     * @throws Exception
     */
    public static void delete(CuratorFramework client, String path) throws Exception{
        log.info("准备删除节点:{}",path);
        client.delete().guaranteed()//就算网络遇见抖动,只要连接成功,也会保证删除
            .deletingChildrenIfNeeded()//递归删除子节点
            .withVersion(getStat(client, path).getVersion()).forPath(path);
        log.info("完成删除节点:{}",path);
    }
    
    /**
     * @author 七脉
     * 描述:查询节点元数据,查询、修改、删除时需要该数据的信息作为参数
     *        同样也是判断节点是否存在的方法
     * @param client
     * @param path
     * @return
     * @throws Exception
     */
    public static Stat getStat(CuratorFramework client, String path) throws Exception{
        log.info("准备获取 节点:{}的stat",path);
        Stat stat = client.checkExists().forPath(path);
        if(null==stat){
            log.info("获取节点:{} 不存在或已删除",path);
        }else{
            log.info("完成获取节点:{} stat信息, version:{}",path,stat.getVersion());
        }
        return stat;
    }
    
    /**
     * @author 七脉
     * 描述:测试客户端的三个状态
     *        client.isStarted();//官方已经建议使用该方法,后续升级可能不会对其维护,请不要再使用。
     */
    public static void status(){
        CuratorFramework client = client();
        //client.isStarted();//官方已经建议使用该方法,后续升级可能不会对其维护,请不要再使用。
        log.info("客户端状态:{}", client.getState());
        client.start();
        log.info("客户端状态:{}", client.getState());
        client.close();
        log.info("客户端状态:{}", client.getState());
    }
    
}

pom配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<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>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
    </parent>
    
    <groupId>com.qy.learn</groupId>
    <artifactId>qy-learn-zk-curator</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>
    
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
        <maven.test.skip>true</maven.test.skip>
        <java.version>1.8</java.version>
        <spring.boot.version>2.0.1.RELEASE</spring.boot.version>
        <qy.code.version>0.0.1-SNAPSHOT</qy.code.version>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <!-- 不使用springboot默认log -->
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.12</version>
            <!-- 排除冲突jar -->
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/org.apache.curator/curator-framework -->
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-framework</artifactId>
            <version>4.1.0</version>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/org.apache.curator/curator-recipes -->
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>4.1.0</version>
        </dependency>
        
        
    </dependencies>
    
    <repositories>
        <repository>
            <id>nexus-aliyun</id>
            <name>Nexus aliyun</name>
            <url>http://maven.aliyun.com/nexus/content/groups/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>nexus-aliyun</id>
            <name>Nexus aliyun</name>
            <url>http://maven.aliyun.com/nexus/content/groups/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
    
    
    <build>
        <plugins>
            <!-- 要将源码放上去,需要加入这个插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <configuration>
                    <attach>true</attach>
                </configuration>
                <executions>
                    <execution>
                        <phase>compile</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project> 

源码:https://pan.baidu.com/s/1WxW0NU6p7oAiK9O3Vtq-Hg

猜你喜欢

转载自www.cnblogs.com/zwcry/p/10442332.html
今日推荐