Test

Enumerable.Range(1, 5).ToList().ForEach(i =>
{
Task.Run(() =>
{ var lockHelper = new ZooKeeperLockHelper("localhost:5181");
lockHelper.OnAcquireLock += (id) =>
{
var random = new Random().Next(10);
Log.Debug("NodeId {@id} executing.....Sleep {@ms} ms", id, random * 1000); Thread.Sleep(random * 1000);
Log.Debug("NodeId {@id} executing success", id); return Task.CompletedTask;
}; lockHelper.AcquireLock(); }); });
using org.apache.zookeeper;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks; namespace RedisDemo
{
public class ZooKeeperLockHelper : Watcher, IDisposable
{ #region event public event Func<long, Task> OnAcquireLock;
#endregion private bool _disposed; private ZooKeeper _zooKeeper;
private Event.KeeperState _currentState;
private AutoResetEvent _notifyEvent = new AutoResetEvent(false); private string _connectionString; private bool _hasAcquireLock;
private string _lockPath;
private long _currentNodeId; private static readonly string DEFAULT_PATH = "/zk";
private static readonly string NODE_NAME = "node-"; public ZooKeeperLockHelper(string connectionString)
{
_connectionString = connectionString;
this.Initialize(_connectionString, TimeSpan.FromSeconds(60));
} public void AcquireLock(string path = "")
{
if (this._hasAcquireLock)
{
FireAcquireLock(this._currentNodeId).Wait();
return;
} if (!WaitConnected(TimeSpan.FromSeconds(10)))
{
throw new Exception($"{_connectionString} Cannot Connect ZooKeeper");
} _lockPath = path;
if (string.IsNullOrEmpty(_lockPath))
{
_lockPath = DEFAULT_PATH;
} var nodePath = _lockPath + "/" + NODE_NAME; var spath = this._zooKeeper.createAsync(
nodePath, Encoding.UTF8.GetBytes("data"),
ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.EPHEMERAL_SEQUENTIAL).Result;
this._currentNodeId = ParseNodeId(spath); var reuslt = this._zooKeeper.getChildrenAsync(_lockPath, true).GetAwaiter().GetResult();
Log.Debug("#-> Begin Acquire Lock CurrentId {@id}", _currentNodeId); if (this.IsMinNodeId(reuslt, this._currentNodeId))
{
lock (this)
{
if (!this._hasAcquireLock)
{
Log.Debug("NodeId {@id} Direct Acquire Lock", _currentNodeId);
this._hasAcquireLock = true;
this.FireAcquireLock(this._currentNodeId).Wait();
} }
} } protected bool IsMinNodeId(ChildrenResult childrenResult, long nodeId)
{
if (nodeId == 0 || childrenResult == null || childrenResult.Children.Count == 0)
return false; var nodeIds = new List<long>(); foreach (var item in childrenResult.Children)
{
nodeIds.Add(ParseNodeId(item));
} if (nodeIds.Count > 0 && nodeIds.Min() == nodeId)
{
return true; }
return false;
} protected long ParseNodeId(string path)
{
var m = Regex.Match(path, "(\\d+)");
if (m.Success)
{
return long.Parse(m.Groups[0].Value);
}
return 0L;
} protected void Initialize(String connectionString, TimeSpan sessionTimeout)
{
this._zooKeeper = new ZooKeeper(connectionString, (int)sessionTimeout.TotalMilliseconds, this);
} public Task FireAcquireLock(long id)
{
this.OnAcquireLock(id).Wait();
this.CloseConnection();
Log.Debug("NodeId {@id} Close ZooKeeper Success", id);
return Task.CompletedTask;
} public bool WaitConnected(TimeSpan timeout)
{
var continueWait = false;
while (this._currentState != Event.KeeperState.SyncConnected)
{
continueWait = _notifyEvent.WaitOne(timeout);
if (!continueWait)
{
return false;
}
}
return true;
} protected void CloseConnection()
{
if (_disposed)
{
return;
}
_disposed = true; if (_zooKeeper != null)
{
try
{
this._zooKeeper.closeAsync().ConfigureAwait(false).GetAwaiter().GetResult();
}
catch { } }
} #region Watcher Impl public override Task process(WatchedEvent @event)
{
if (@event.getState() == Event.KeeperState.SyncConnected)
{
if (String.IsNullOrEmpty(@event.getPath()))
{
this._currentState = @event.getState();
this._notifyEvent.Set();
} var path = @event.getPath();
if (!string.IsNullOrEmpty(path))
{
if (path.Equals(this._lockPath))
{
Log.Debug("NodeId {@id} Start Watcher Callback", this._currentNodeId); if (this._hasAcquireLock)
{
Log.Debug("NodeId {@id} Has Acquire Lock return", this._currentNodeId);
return Task.CompletedTask;
} Task.Run(() =>
{
var childrenResult = _zooKeeper.getChildrenAsync(this._lockPath, this).Result; if (IsMinNodeId(childrenResult, this._currentNodeId))
{
lock (this)
{
if (!this._hasAcquireLock)
{
Log.Debug("NodeId {@id} Acquire Lock", this._currentNodeId);
this._hasAcquireLock = true;
this.FireAcquireLock(this._currentNodeId).Wait();
}
}
}
}); //_zooKeeper.getChildrenAsync(_lockPath, this); }
}
} return Task.CompletedTask;
} public void Dispose()
{
this.CloseConnection();
} #endregion
}
}

ZooKeeper Distributed lock的更多相关文章

  1. distributed lock manager (DLM)(分布式管理锁)

    A distributed lock manager (DLM) provides distributed software applications with a means to synchron ...

  2. Redis Distributed lock

    using StackExchange.Redis; using System; using System.Collections.Generic; using System.Linq; using ...

  3. 基于ZooKeeper的分布式锁和队列

    在分布式系统中,往往需要一些分布式同步原语来做一些协同工作,上一篇文章介绍了Zookeeper的基本原理,本文介绍下基于Zookeeper的Lock和Queue的实现,主要代码都来自Zookeeper ...

  4. zookeeper实现分布式锁服务

    A distributed lock base on zookeeper. zookeeper是hadoop下面的一个子项目, 用来协调跟hadoop相关的一些分布式的框架, 如hadoop, hiv ...

  5. How to do distributed locking

    How to do distributed locking 怎样做可靠的分布式锁,Redlock 真的可行么? 本文是对 Martin Kleppmann 的文章 How to do distribu ...

  6. 基于Apache Curator框架的ZooKeeper使用详解

    一 简介 Apache Curator是一个比较完善的ZooKeeper客户端框架,通过封装的一套高级API 简化了ZooKeeper的操作.通过查看官方文档,可以发现Curator主要解决了三类问题 ...

  7. 基于zookeeper实现的分布式锁

    基于zookeeper实现的分布式锁 2011-01-27 • 技术 • 7 条评论 • jiacheo •14,941 阅读 A distributed lock base on zookeeper ...

  8. zookeeper生产最广泛使用java客户端curator介绍及其它客户端比较

    关于zookeeper的原理解析,可以参见zookeeper核心原理详解,本文所述大多数实践基于对zookeeper原理的首先理解. Curator是Netflix公司开源的一个Zookeeper客户 ...

  9. 01 . 消息队列之(Kafka+ZooKeeper)

    消息队列简介 什么是消息队列? 首先,我们来看看什么是消息队列,维基百科里的解释翻译过来如下: 队列提供了一种异步通信协议,这意味着消息的发送者和接受者不需要同时与消息保持联系,发送者发送的消息会存储 ...

随机推荐

  1. 永久激活2018.3.5版phpstorm

    下载文件JetbrainsIdesCrack-4.2.jar 文件在后面的附件 配置文件在访达的应用程序中找到phpstorm或者idea,右击,选择显示包含内容,点击显示进入Contents-> ...

  2. 使用IntersectionObserver制作滚动动画以及其他记录

    前言 最近在重做公司项目的主页,正好新来了个UI,整个都重新设计了一下,动画还挺多的.我之前没有怎么玩过这些,踩了挺多坑,最后找到了目前而言最合适的方法,现在做一个记录. 需要把原来的主页从项目中抽出 ...

  3. PAT (Advanced Level) Practice 1008 Elevator (20 分) (模拟)

    The highest building in our city has only one elevator. A request list is made up with N positive nu ...

  4. bootstrap-table中时间戳转换为日期格式。

    { field: 'createdTime', title: '创建时间', formatter: function (value, row, index) { return changeDateFo ...

  5. 题解 P5712 【【深基3.例4】Apples】

    题目传送门 思路 仔细读题后,我们可以发现,输出可以分成\(2\)种情况,apple加s与apple不加s,所以我们可以使用if/else来实现. 接着,我们读入n. int n; cin>&g ...

  6. IDEA科学使用

    今天莫名激活码又用不起了有能力的支持正版吧 ,要用的时候又去网上到处找然后发现各种用不了,去淘宝又怕被骗博主就是过来人 ,总算下定决心写一篇一劳永逸的方法.. 方法一:合理使用激活码 用过idea的都 ...

  7. JAVA并发同步互斥实现方式总结

    大家都知道加锁是用来在并发情况防止同一个资源被多方抢占的有效手段,加锁其实就是同步互斥(或称独占)也行,即:同一时间不论有多少并发请求,只有一个能处理,其余要么排队等待,要么放弃执行.关于锁的实现网上 ...

  8. Linux安装U盘启动报错Failed to load ldlinux.c32

    报错信息 使用U盘安装linux无法正常启动 Start booting from USB device... SYSLINUX 5.10 EDD 2013-06-04 Copyright (C) 1 ...

  9. 小程序y轴拖动

    需求场景 小程序在y轴方向 拖动 一小段距离 解决方案 1.监听 元素 2.绑定 点击 和 移动 事件 3.数据处理 代码 <view animation="{{item.animat ...

  10. mysql 基础sql语法总结 (二)DML

    二.DML(增.删.改) 1)插入数据 第一种写法:INSERT INTO 表名 (列名1,列名2,,......)VALUES(列值1,列值2,......) 第二种写法:INSERT INTO 表 ...