ABP DistributedLock
ABP DistributedLock
2023/6/1
➡️

DistributedLock

DistributedLock 一个支持分布式锁的开源库 https://github.com/madelson/DistributedLock

var redisDistributedLock = new RedisDistributedLock(name, connectionString);
//自动释放锁,会一直尝试获取锁,
using (redisDistributedLock.Acquire())
{
  //持有锁
}

虽然 Acquire 将阻塞直到锁可用,但还有一个 TryAcquire 变体,如果无法获取锁(由于在别处持有 ),则返回 null

using (var handle = redisDistributedLock.TryAcquire())
{
    if (handle != null)
    {
        // 我们获得锁
    }
    else
    {
        // 别人获得锁
    }
}

支持异步和依赖注入,依赖注入

services.AddSingleton<IDistributedLockProvider>(_ =>
new RedisDistributedSynchronizationProvider(name,myConnectionString));

public class SomeService
{
    private readonly IDistributedLockProvider _synchronizationProvider;

    public SomeService(IDistributedLockProvider synchronizationProvider)
    {
        this._synchronizationProvider = synchronizationProvider;
    }

    public void InitializeUserAccount(int id)
    {
        // 通过provider构造lock
        var @lock = this._synchronizationProvider.CreateLock($"UserAccount{id}");
        using (@lock.Acquire())
        {
            //
        }

        using (this._synchronizationProvider.AcquireLock($"UserAccount{id}"))
        {
            //
        }
    }
}
👍🎉🎊