zoukankan      html  css  js  c++  java
  • zk客户端及锁的使用

    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);
    
  • 相关阅读:
    打理自己的生活
    多线程练习 -- 自定义NSOperation
    多线程练习 -- 单例设计模式
    IOS学习笔记 -- 多线程
    画画板 -- 可自定义线的宽度和颜色
    手势识别器基本练习
    触摸事件练习 -- 手势解锁
    触摸事件练习 -- 画画板(截屏分类)
    Main.storyboard
    Quartz2D练习 -- 裁剪图片分类
  • 原文地址:https://www.cnblogs.com/PythonOrg/p/14596405.html
Copyright © 2011-2022 走看看