在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文库

 

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部