public ZookeeperConfigurationWatcher(ZookeeperConfigurationProvider zookeeperConfigurationProvider)
        {
            this.zookeeperConfigurationProvider = zookeeperConfigurationProvider;
            var options = zookeeperConfigurationProvider.ZookeeperConfigurationSource.ZookeeperOptions;

            zookeeperHelper = new ZookeeperHelper(options.Address, options.RootPath);
            //初次连接后,立即
            zookeeperHelper.OnConnected += () =>
            {
                if (options.Scheme != AuthScheme.World)
                {
                    zookeeperHelper.Authorize(options.Scheme, options.Auth);
                }
                zookeeperConfigurationProvider.Reload();
            };
            zookeeperHelper.Connect();
            //int timeOut = 10;
            //while (!zookeeperHelper.Connected && timeOut-- > 0)
            //{
            //    Thread.Sleep(1000); //停一秒,等待连接完成
            //}
            if (!zookeeperHelper.Connected)
            {
                throw new TimeoutException($"connect to zookeeper [{options.Address}] timeout");
            }

            if (options.ReloadOnChange)
            {
                //监听根节点下所有的znode节点,当任意节点发生改变后,即立刻重新加载
                zookeeperHelper.WatchAllAsync(ze =>
                {
                    if (ze.Type != ZookeeperEvent.EventType.None)
                    {
                        //使用一个异步去完成,同步会造成死锁
                        Task.Run(() =>
                        {
                            zookeeperConfigurationProvider.Reload();
                        });
                    }
                }).Wait();
            }
        }
Пример #2
0
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="lockerPath">分布式锁的根路径</param>
        /// <param name="sessionTimeout">回话过期时间</param>
        /// <param name="address">集群地址</param>
        public ZookeeperLocker(string lockerPath, int sessionTimeout, params string[] address)
        {
            this.address = address.ToArray();

            zookeeperHelper = new ZookeeperHelper(address, lockerPath);
            if (sessionTimeout > 0)
            {
                zookeeperHelper.SessionTimeout = sessionTimeout;
            }
            if (!zookeeperHelper.Connect())
            {
                throw new Exception("connect failed:" + string.Join(",", address));
            }
            lock (locker)
            {
                if (!zookeeperHelper.Exists())//根节点不存在则创建
                {
                    zookeeperHelper.SetData("", "", true);
                }
            }
        }
Пример #3
0
 public DefaultWatcher(ZookeeperHelper zookeeperHelper, EventWaitHandle ewh)
 {
     this.ewh             = ewh;
     this.zookeeperHelper = zookeeperHelper;
 }