/// <summary> /// 生成一个锁 /// </summary> /// <returns>返回锁名</returns> public string CreateLock() { var path = Guid.NewGuid().ToString().Replace("-", ""); while (zookeeperHelper.Exists(path)) { path = Guid.NewGuid().ToString().Replace("-", ""); } return(CreateLock(path)); }
/// <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); } } }