• 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);
    
  • 相关阅读:
    深入理解RunLoop
    Universal Framework for iOS
    Framework的制作流程,Xode-6.0.1
    Xcode 6制作动态及静态Framework
    Volley与Picasso的对比
    WebView全面学习(二)-- Native与js双方通信
    WebView全面学习(一)--常用类和方法
    Hybrid框架安全隐患分析
    Android笔记--View绘制流程源码分析(二)
    Android笔记--View绘制流程源码分析(一)
  • 原文地址:https://www.cnblogs.com/PythonOrg/p/14596405.html
Copyright © 2020-2023  润新知