MyRedis分布式加锁解锁

avatar
作者
筋斗云
阅读量:0

在C#中使用MyRedis实现分布式锁通常涉及到SET命令配合选项NX(唯一性)和PX(过期时间)。以下是一个简单的示例,展示了如何使用StackExchange.Redis客户端在C#中实现分布式锁和解锁。

首先,确保已经安装了StackExchange.Redis库

Install-Package StackExchange.Redis

简单示例代码 

using StackExchange.Redis; using System; using System.Threading.Tasks;   public class RedisDistributedLock {     private readonly ConnectionMultiplexer _redisConnection;     private readonly IDatabase _database;       public RedisDistributedLock(string configuration)     {         _redisConnection = ConnectionMultiplexer.Connect(configuration);         _database = _redisConnection.GetDatabase();     }       public async Task<bool> AcquireLock(string lockKey, string value, int expireTime)     {         // 使用SET命令加锁,条件是键不存在,并设置过期时间         return await _database.StringSetAsync(lockKey, value, expireTime, When.NotExists);     }       public async Task<bool> ReleaseLock(string lockKey, string value)     {         // 获取键对应的值,并且比较是否与传入的值相同,相同则删除键以释放锁         var currentValue = await _database.StringGetAsync(lockKey);         if (currentValue.ToString() == value)         {             return await _database.KeyDeleteAsync(lockKey);         }         return false;     } }   // 使用示例 var lockClient = new RedisDistributedLock("localhost:6379"); string lockKey = "my_lock"; string lockValue = Guid.NewGuid().ToString(); // 生成唯一值 int lockExpireTime = 5000; // 锁的过期时间,单位毫秒   // 尝试获取锁 bool isLockAcquired = await lockClient.AcquireLock(lockKey, lockValue, lockExpireTime);   if (isLockAcquired) {     try     {         // 业务逻辑         Console.WriteLine("Lock acquired. Exclusive access to the resource.");     }     finally     {         // 释放锁         bool isLockReleased = await lockClient.ReleaseLock(lockKey, lockValue);         if (isLockReleased)         {             Console.WriteLine("Lock released.");         }         else         {             Console.WriteLine("Unable to release the lock.");         }     } } else {     Console.WriteLine("Unable to acquire lock."); }

完整示例项目下载地址:MyRedis分布式加锁解锁.rar_myredis资源-CSDN文库

 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!