/PlayingWithDistributedLock

Try out to make distributed locks using Redis.

Primary LanguageC#

Playing with distributed locks using Redis

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.

Resources

Clients

  • [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.

Code snippets

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();
}

Setup a redis server on Windows.

  1. Download the redis server (zip version) from MicrosoftArchive/redis/releases
  2. Run the server: redis-server.exe
  3. Run the client (optional): redis-cli.exe | Redis commands

Install it from: Chocolatey Galery.

This flowchart is represent the steps.

Flowchart