This small .NET application is an example of acquiring locks in a distributed environment.
I prefer using Azure Service Bus with the SessionQueue feature to avoid race conditions and handle messages for the same resource.
- Distributed locks with Redis 📓Official Redis page
- Using the Observer design pattern for to release the lock
- Using the Polly library to wait and retry to acquire a lock
- Improve memory allocation 📓Devindran Ramadass - RecyclableMemoryStreamManager and ArrayPoolBufferWriter
- [StackExchange.Redis 👤Stack Overflow - Most popular and stable client. Interface for IDatabase
- [StackExchange.Redis.Extensions 👤Ugo Lattanzi - This library extends StackExchange.Redis. IRedisDatabase
- RedLock.net 👤Sam Cook - An implementation of a distributed lock algorithm
Try out distributed cache with Redis.
public interface ILockFactory
{
ILockObject AcquireLock(string key, TimeSpan expiration, int retryCount = 0, TimeSpan sleepDuration = default);
Task<ILockObject> AcquireLockAsync(string key, TimeSpan expiration, int retryCount = 0, TimeSpan sleepDuration = default, CancellationToken cancelToken = default);
}
public interface ILockObject : IDisposable
{
// Did I get a lock or not?
bool IsAcquired { get; }
// Release the lock, if it still exists and returns true, otherwise false.
bool Release();
Task<bool> ReleaseAsync();
}
- Download the redis server (zip version) from MicrosoftArchive/redis/releases
- Run the server: redis-server.exe
- Run the client (optional): redis-cli.exe | Redis commands
Install it from: Chocolatey Galery.