/// <summary> /// 创建Leader选举对象 /// </summary> /// <param name="id">每个Leader选举的参与者都有一个ID标识,用于区分各个参与者。</param> /// <param name="autoRequue">是否在由于网络问题造成与服务器断开连接后,自动参与到选举队列中。</param> /// <param name="delayTimeMillis">延迟选举的时间,主要是针对网络闪断的情况,给Leader以重连并继续成为Leader的机会,一般5秒合适。</param> /// <param name="client">ZKClient</param> /// <param name="leaderPath">选举的路径</param> /// <param name="listener">成为Leader后执行的的监听器</param> public ZKLeaderDelySelector(string id, bool autoRequue, int delayTimeMillis, ZKClient client, string leaderPath, ZKLeaderSelectorListener listener) { this.delayTimeMillis = delayTimeMillis; this.id = id; this.client = client; this.autoRequeue = autoRequue; this.leaderPath = leaderPath; this._lock = ZKDistributedDelayLock.NewInstance(client, leaderPath); this._lock.SetLockNodeData(this.id); this.listener = listener; SetFactory(); stateListener = new ZKStateListener().StateChanged( (state) => { if (state == KeeperState.SyncConnected) { //如果重新连接 if (!isInterrupted) { Requeue(); } } }); }
public void TestDistributedDelayLock() { _zkClient.CreateRecursive(lockPath, null, CreateMode.Persistent); int index = 0; List <string> msgList = new List <string>(); for (int i = 0; i < 5; i++) { Task.Factory.StartNew(() => { ZKClient zkClient1 = ZKClientBuilder.NewZKClient() .Servers(string.Format("{0}:{1}", TestUtil.ip, TestUtil.port)) .SessionTimeout(10000) .Build(); ZKDistributedDelayLock _lock = ZKDistributedDelayLock.NewInstance(zkClient1, lockPath); autoReset.WaitOne(); _lock.Lock(); Console.WriteLine(Thread.CurrentThread.Name + ":lock...."); msgList.Add(Thread.CurrentThread.Name + ":unlock"); try { Thread.Sleep(1000); } catch (ThreadInterruptedException e) { } Console.WriteLine(Thread.CurrentThread.Name + ":unlock...."); _lock.UnLock(); }); Interlocked.Increment(ref index); } autoReset.Set(); int size = TestUtil.WaitUntil(5, () => { return(msgList.Count); }, new TimeSpan(0, 0, 200)); Assert.True(size == 5); }