SpringBoot教程(八)——集成Zookeeper

 1.pom依赖:


    org.apache.curator
    curator-recipes
    5.1.0

2.Zookeeper配置类:

/**
 * @Classname ZookeeperConfig 
 * @Description TODO
 * @Date 2021/7/13 11:08
 * @Created by zlx
 */
@Configuration
public class ZookeeperConfig {
    private String zkAddress = "192.168.33.131:2181,192.168.33.131:2182,192.168.33.131:2183"; //地址和端口号192 .168 .23 .129:2181, 192.168 .23 .128:2181
    private int sessionTimeout = 60000;//会话超时时间 单位ms
    private int connectionTimeout = 15000;//连接超时时间 单位ms
    private String nameSpace = "zjzyzlx";//默认为操作的根节点,为了实现不同的Zookeeper业务之间的隔离,所有操作都是基于该目录进行的
    private String lockNode = "/123";//默认为操作的根节点,为了实现不同的Zookeeper业务之间的隔离,所有操作都是基于该目录进行的
    private int baseSleepTimeMs = 3000;//重试间隔时间
    private int maxRetries = 10;//重试次数

    @Bean(initMethod = "start", destroyMethod = "close")
    public CuratorFramework curatorFramework() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(baseSleepTimeMs, maxRetries);
        return CuratorFrameworkFactory.builder()
                .connectString(zkAddress)
                .sessionTimeoutMs(sessionTimeout)
                .connectionTimeoutMs(connectionTimeout)
                .retryPolicy(retryPolicy)
                .namespace(nameSpace)
                .build();
    }
}

3.自定义监听器

public class ZKNodeEventListener implements CuratorCacheListener {

    @Override
    public void event(Type type, ChildData childData, ChildData childData1) {
        switch (type) {
            case NODE_CHANGED:
                System.out.println("节点数据修改");
                System.out.println("修改前的节点路径:" + childData.getPath());
                System.out.println("修改前的节点数据:" + new String(childData.getData()));
                System.out.println("修改后的节点路径:" + childData1.getPath());
                System.out.println("修改后的节点数据:" + new String(childData1.getData()));
                break;
            case NODE_CREATED:
                System.out.println("新增节点");
                System.out.println("新增节点的路径"+childData1.getPath());
                System.out.println("新增节点的数据:" + new String(childData1.getData()));
                break;
            case NODE_DELETED:
                System.out.println("删除节点");
                System.out.println("删除节点的路径"+childData.getPath());
                System.out.println("删除节点的数据:" + new String(childData.getData()));
                break;
            default:
                break;
        }
        System.out.println("----------------------------");
    }
}

4.封装工具类

@Component
@Slf4j
public class ZookeeperService {

    @Autowired
    private CuratorFramework client;

    @Autowired
    private InterProcessMutex lock;

    /**
     * 创建永久Zookeeper节点
     *
     * @param nodePath  节点路径(如果父节点不存在则会自动创建父节点),如:/curator
     * @param nodeValue 节点数据
     * @return 返回创建成功的节点路径
     */
    public String createPersistentNode(String nodePath, String nodeValue) {
        try {
            return client.create().creatingParentsIfNeeded().forPath(nodePath, nodeValue.getBytes());
        } catch (Exception e) {
            log.error("创建永久Zookeeper节点失败,nodePath:{},nodeValue:{}", nodePath, nodeValue, e);
        }
        return null;
    }

    /**
     * 创建永久有序Zookeeper节点
     *
     * @param nodePath  节点路径(如果父节点不存在则会自动创建父节点),如:/curator
     * @param nodeValue 节点数据
     * @return 返回创建成功的节点路径
     */
    public String createSequentialPersistentNode(String nodePath, String nodeValue) {
        try {
            return client.create().creatingParentsIfNeeded()
                    .withMode(CreateMode.PERSISTENT_SEQUENTIAL)
                    .forPath(nodePath, nodeValue.getBytes());
        } catch (Exception e) {
            log.error("创建永久有序Zookeeper节点失败,nodePath:{},nodeValue:{}", nodePath, nodeValue, e);
        }
        return null;
    }

    /**
     * 创建临时Zookeeper节点
     *
     * @param nodePath  节点路径(如果父节点不存在则会自动创建父节点),如:/curator
     * @param nodeValue 节点数据
     * @return 返回创建成功的节点路径
     */
    public String createEphemeralNode(String nodePath, String nodeValue) {
        try {
            return client.create().creatingParentsIfNeeded()
                    .withMode(CreateMode.EPHEMERAL)
                    .forPath(nodePath, nodeValue.getBytes());
        } catch (Exception e) {
            log.error("创建临时Zookeeper节点失败,nodePath:{},nodeValue:{}", nodePath, nodeValue, e);
        }
        return null;
    }

    /**
     * 创建临时有序Zookeeper节点
     *
     * @param nodePath  节点路径(如果父节点不存在则会自动创建父节点),如:/curator
     * @param nodeValue 节点数据
     * @return 返回创建成功的节点路径
     * @since 1.0.0
     */
    public String createSequentialEphemeralNode(String nodePath, String nodeValue) {
        try {
            return client.create().creatingParentsIfNeeded()
                    .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                    .forPath(nodePath, nodeValue.getBytes());
        } catch (Exception e) {
            log.error("创建临时有序Zookeeper节点失败,nodePath:{},nodeValue:{}", nodePath, nodeValue, e);
        }
        return null;
    }

    /**
     * 检查Zookeeper节点是否存在
     *
     * @param nodePath 节点路径
     * @return boolean 如果存在则返回true
     */
    public boolean checkExists(String nodePath) {
        try {
            Stat stat = client.checkExists().forPath(nodePath);

            return stat != null;
        } catch (Exception e) {
            log.error("检查Zookeeper节点是否存在出现异常,nodePath:{}", nodePath, e);
        }
        return false;
    }

    /**
     * 获取某个Zookeeper节点的所有子节点
     *
     * @param nodePath 节点路径
     * @return 返回所有子节点的节点名
     */
    public List getChildren(String nodePath) {
        try {
            return client.getChildren().forPath(nodePath);
        } catch (Exception e) {
            log.error("获取某个Zookeeper节点的所有子节点出现异常,nodePath:{}", nodePath, e);
        }
        return null;
    }

    /**
     * 获取某个Zookeeper节点的数据
     *
     * @param nodePath 节点路径
     * @return 节点存储的数据
     */
    public String getData(String nodePath) {
        try {
            return new String(client.getData().forPath(nodePath));
        } catch (Exception e) {
            log.error("获取某个Zookeeper节点的数据出现异常,nodePath:{}", nodePath, e);
        }
        return null;
    }

    /**
     * 设置某个Zookeeper节点的数据
     *
     * @param nodePath 节点路径
     */
    public void setData(String nodePath, String newNodeValue) {
        try {
            client.setData().forPath(nodePath, newNodeValue.getBytes());
        } catch (Exception e) {
            log.error("设置某个Zookeeper节点的数据出现异常,nodePath:{}", nodePath, e);
        }
    }

    /**
     * 删除某个Zookeeper节点
     *
     * @param nodePath 节点路径
     */
    public void delete(String nodePath) {
        try {
            client.delete().guaranteed().forPath(nodePath);
        } catch (Exception e) {
            log.error("删除某个Zookeeper节点出现异常,nodePath:{}", nodePath, e);
        }
    }

    /**
     * 级联删除某个Zookeeper节点及其子节点
     *
     * @param nodePath 节点路径
     */
    public void deleteChildrenIfNeeded(String nodePath) {
        try {
            client.delete().guaranteed().deletingChildrenIfNeeded().forPath(nodePath);
        } catch (Exception e) {
            log.error("级联删除某个Zookeeper节点及其子节点出现异常,nodePath:{}", nodePath, e);
        }
    }

    /**
     * 监听节点变化
     *
     * @param nodePath 节点路径
     */
    public void cacheListener(String nodePath) {
        //1.创建curatorCache对象
        CuratorCache curatorCache = CuratorCache.build(client, nodePath);
        //2.注册监听器
        curatorCache.listenable().addListener(new ZKNodeEventListener());
        //3.开启监听:true加载缓冲数据
        curatorCache.start();
    }
}

你可能感兴趣的:(SpringBoot,java,zookeeper,spring,boot)