Implementing Distributed Locking with Redis and IDistributedLock

Implementing Distributed Locking with Redis and IDistributedLock Distributed locking is a critical feature for ensuring resource safety in distributed applications. Here’s how you can implement a distributed lock using the IDistributedLock interface and Redis as the backing store, leveraging the StackExchange.Redis library. Step 1: Implement the IDistributedLock Interface Let’s start by creating the RedisDistributedLock class to implement the IDistributedLock interface: using StackExchange.Redis; using System; using System.Threading.Tasks; public class RedisDistributedLock : IDistributedLock { private readonly IDatabase _database; private readonly string _lockKey; private string _lockToken; public RedisDistributedLock(IDatabase database, string lockKey) { _database = database; _lockKey = lockKey; _lockToken = Guid.NewGuid().ToString(); } public async Task<bool> AcquireLockAsync(string resource, TimeSpan leaseTime) { _lockToken = Guid.NewGuid().ToString(); return await _database.StringSetAsync(resource, _lockToken, leaseTime, When.NotExists); } public async Task RenewLockAsync(TimeSpan leaseTime) { if (!await _database.StringGetAsync(_lockKey).ConfigureAwait(false).Equals(_lockToken)) { throw new InvalidOperationException("Cannot renew a lock that is not held."); } await _database.KeyExpireAsync(_lockKey, leaseTime); } public async Task ReleaseLockAsync() { var token = await _database.StringGetAsync(_lockKey); if (token == _lockToken) { await _database.KeyDeleteAsync(_lockKey); } } public void Dispose() { ReleaseLockAsync().GetAwaiter().GetResult(); } } Step 2: Create a Sample Console Application Next, build a console application to demonstrate the functionality of the RedisDistributedLock: ...

March 15, 2025 · 2 min · TC

Mastering Aspect-Oriented Programming (AOP): Concepts and Examples

RedisDistributedLock Implementation in Aspect-Oriented Programming (AOP) Aspect-Oriented Programming (AOP) lends itself well to distributed resource management tasks such as locking. Below is an implementation of a Redis-based distributed lock using the StackExchange.Redis library, focusing on resource isolation and concurrency control. RedisDistributedLock Class Here is the complete implementation: using StackExchange.Redis; using System; using System.Threading.Tasks; public class RedisDistributedLock : IDisposable { private readonly IDatabase _redisDb; private readonly string _lockKey; private readonly string _lockValue; private bool _acquired; public RedisDistributedLock(IDatabase redisDb, string resourceKey) { _redisDb = redisDb; _lockKey = $"lock:{resourceKey}"; _lockValue = Guid.NewGuid().ToString(); // random token } /// <summary> /// Attempts to acquire a lock for the specified lock key with a given expiry. /// </summary> /// <param name="expiry">Duration for lock expiry.</param> /// <returns>True if the lock was acquired; otherwise, false.</returns> public async Task<bool> AcquireAsync(TimeSpan expiry) { _acquired = await _redisDb.StringSetAsync( key: _lockKey, value: _lockValue, expiry: expiry, when: When.NotExists); return _acquired; } /// <summary> /// Releases the lock if it’s still held by this instance. /// </summary> public async Task ReleaseAsync() { if (_acquired) { // Verify token before deleting. var currentValue = await _redisDb.StringGetAsync(_lockKey); if (currentValue == _lockValue) { await _redisDb.KeyDeleteAsync(_lockKey); } _acquired = false; } } /// <summary> /// Cleanup method ensuring the lock is freed. /// </summary> public void Dispose() { ReleaseAsync().GetAwaiter().GetResult(); } } Acquiring and Releasing the Lock Using the RedisDistributedLock class to acquire and release locks ensures concurrency control in distributed systems. ...

March 15, 2025 · 2 min · Taner