首页 > 代码库 > .net 分布式架构之分布式锁实现
.net 分布式架构之分布式锁实现
分布式锁
经常用于在解决分布式环境下的业务一致性和协调分布式环境。
实际业务场景中,比如说解决并发一瞬间的重复下单,重复确认收货,重复发现金券等。
使用分布式锁的场景一般不能太多。
开源地址:http://git.oschina.net/chejiangyi/XXF.BaseService.DistributedLock
开源相关群: .net 开源基础服务 238543768
这里整理了C#.net关于redis分布式锁和zookeeper分布式锁的实现,仅用于研究。(可能有bug)
采用ServiceStack.Redis实现Redis分布式锁
1 |
RedisDistributedLock( redisserver, LockResult TryGetDistributedLock(TimeSpan? getlockTimeOut, TimeSpan? (lockresult == DistributedLockException(= ._lock = =.Format(= (._lock != (_client != .Format(
来自网络的java实现Redis分布式锁(C#版)
RedisDistributedLockFromJava( redisserver, LockResult TryGetDistributedLock(TimeSpan? getlockTimeOut, TimeSpan? (lockresult == DistributedLockException( taskexpiredMilliseconds = (taskrunTimeOut != ? ()taskrunTimeOut.Value.TotalMilliseconds : ( getlockexpiredMilliseconds = (getlockTimeOut != ? ()getlockTimeOut.Value.TotalMilliseconds : hassleepMilliseconds = ( ( redisclient = value = CurrentUnixTimeMillis() + taskexpiredMilliseconds + acquired = redisclient.Add<>(@lock, value, TimeSpan.FromMilliseconds(taskexpiredMilliseconds + (acquired == = oldValueBytes = (oldValueBytes != && BitConverter.ToInt64(oldValueBytes, ) < getValueBytes = o1 = redisclient.ExpireEntryIn(@lock, TimeSpan.FromMilliseconds(taskexpiredMilliseconds + DistributedLockConfig.TaskLockDelayCleepUpTime));= = = (lockresult == (hassleepMilliseconds >==+=.Format(= ()(System.DateTime.UtcNow - System.DateTime(, , , , , (lockresult == LockResult.Success || lockresult == current = ( redisclient = v = (v != (current < BitConverter.ToInt64(v, .Format(
ServiceStack.Redis内部实现版本(较旧)
1 |
RedisDistributedLockFromServiceStack( redisserver, LockResult TryGetDistributedLock(TimeSpan? getlockTimeOut, TimeSpan? (lockresult == DistributedLockException( ( redisClient ==> lockString = (expireTime.ToUnixTimeMs() + = lockExpireString = redisClient.Get<> (!.TryParse(lockExpireString, trans.QueueCommand(r => (t == ==.Format(= ( redisClient =.Format(
Zookeeper 版本实现分布式锁
root = ; lockName; waitNode; myZnode; TimeSpan sessionTimeout = TimeSpan.FromMilliseconds( IList<Exception> exception = List<Exception> ZooKeeprDistributedLockFromJava( config, .lockName = = ZooKeeper(config, sessionTimeout, stat = zk.Exists(root, (stat == zk.Create(root, [ (.autoevent != splitStr = myZnode = zk.Create(root + + lockName + splitStr, [+ IList<> subNodes = zk.GetChildren(root, IList<> lockObjNodes = List<> ( node =+ + lockObjNodes[ (myZnode.Equals(root + + lockObjNodes[ subMyZnode = myZnode.Substring(myZnode.LastIndexOf(, StringComparison.Ordinal) + = lockObjNodes[Array.BinarySearch(alockObjNodes, subMyZnode) - ( waitForLock( stat = zk.Exists(root + + lower, (stat != + System.Threading.Thread.CurrentThread.Name + + root + += AutoResetEvent( r == +-=
以上代码仅做参考,未压测。
代码粘贴有些问题,详细请下载开源包运行研究。
.net 分布式架构之分布式锁实现
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。