首页 > 其他 > 详细

zk客户端及锁的使用

时间:2021-03-30 16:51:53      阅读:26      评论:0      收藏:0      [点我收藏+]

1.生成zk客户端对象

private CuratorFramework buildClient() {
        logger.info("zookeeper registry center init, server lists is: {}.", zookeeperConfig.getServerList());

        CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder().ensembleProvider(new DefaultEnsembleProvider(checkNotNull(zookeeperConfig.getServerList(),
                "zookeeper quorum can‘t be null")))
                .retryPolicy(new ExponentialBackoffRetry(zookeeperConfig.getBaseSleepTimeMs(), zookeeperConfig.getMaxRetries(), zookeeperConfig.getMaxSleepMs())).namespace(zookeeperConfig.getNameSpace());

        //these has default value
        if (0 != zookeeperConfig.getSessionTimeoutMs()) {
            builder.sessionTimeoutMs(zookeeperConfig.getSessionTimeoutMs());
        }
        if (0 != zookeeperConfig.getConnectionTimeoutMs()) {
            builder.connectionTimeoutMs(zookeeperConfig.getConnectionTimeoutMs());
        }
        if (StringUtils.isNotBlank(zookeeperConfig.getDigest())) {
            builder.authorization("digest", zookeeperConfig.getDigest().getBytes(StandardCharsets.UTF_8)).aclProvider(new ACLProvider() {

                @Override
                public List<ACL> getDefaultAcl() {
                    return ZooDefs.Ids.CREATOR_ALL_ACL;
                }

                @Override
                public List<ACL> getAclForPath(final String path) {
                    return ZooDefs.Ids.CREATOR_ALL_ACL;
                }
            });
        }
        zkClient = builder.build();
        zkClient.start();
        try {
            zkClient.blockUntilConnected();
        } catch (final Exception ex) {
            throw new ServiceException(ex);
        }
        return zkClient;
    }

2.zk客户端封装,生成锁对象

String znodeLock = getMasterStartUpLockPath();
 InterProcessMutex mutex = new InterProcessMutex(getZkClient(), znodeLock);

3.锁对象,同步获取锁,异步获取锁

// 同步锁
mutex.acquire();

// 异步锁
boolean flag = mutex.acquire(1,TimeUnit.SECONDS);

zk客户端及锁的使用

原文:https://www.cnblogs.com/PythonOrg/p/14596405.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!