Giới thiệu
Trong bài viết này, chúng ta sẽ discuss cách tạo distributed lock với Redis trong .NET Core.
Khi chúng ta build distributed systems, chúng ta sẽ face multiple processes handle shared resource together. Nó sẽ cause unexpected problems do chỉ một trong chúng có thể utilize shared resource tại một thời điểm!
Chúng ta có thể dùng distributed lock để solve this problem.
Tại sao Distributed Lock?
Như thường lệ, chúng ta dùng lock để handle this problem.
Dưới đây shows some sample codes demonstrating the use of a lock.
public void SomeMethod() {
// Do something...
lock (obj) {
// Do ....
}
// Do something...
}
Tuy nhiên, loại lock này không giúp chúng ta solve the problem well! Đây là in-process lock chỉ có thể solve one process with shared resources.
Đây cũng là main reason tại sao chúng ta cần distributed lock!
Tôi sẽ dùng Redis để tạo một simple distributed lock ở đây.
Và tại sao tôi dùng Redis để làm job này? Vì single-threaded nature của Redis và ability của nó để perform atomic operations.
How To Create A Lock?
Tôi sẽ tạo .NET Core Console application để show you.
Trước next step, chúng ta should run up the Redis server!
StackExchange.Redis là most popular Reids client on .NET, và there is no doubt that we will use it to do the following jobs.
Creating the connection with Redis at first.
/// <summary>
/// The lazy connection.
/// </summary>
private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() => {
ConfigurationOptions configuration = new ConfigurationOptions {
AbortOnConnectFail = false,
ConnectTimeout = 5000,
};
configuration.EndPoints.Add("localhost", 6379);
return ConnectionMultiplexer.Connect(configuration.ToString());
});
/// <summary>
/// Gets the connection.
/// </summary>
/// <value>The connection.</value>
public static ConnectionMultiplexer Connection => lazyConnection.Value;
Để request a lock on a shared resource, chúng ta làm sau.
SET resource_name unique_value NX PX duration
resource_name là value mà all instances của application của bạn would share.
unique_value là something that must be unique to each instance của application của bạn. Và purpose của unique value này là để remove the lock (unlock).
Cuối cùng, chúng ta cũng provide a duration (in milliseconds), sau đó lock sẽ được automatically removed by Redis.
Đây là implementation in C# code.
/// <summary>
/// Acquires the lock.
/// </summary>
/// <returns><c>true</c>, if lock was acquired, <c>false</c> otherwise.</returns>
/// <param name="key">Key.</param>
/// <param name="value">Value.</param>
/// <param name="expiration">Expiration.</param>
static bool AcquireLock(string key, string value, TimeSpan expiration) {
bool flag = false;
try {
flag = Connection.GetDatabase().StringSet(key, value, expiration, When.NotExists);
} catch (Exception ex) {
Console.WriteLine($"Acquire lock fail...{ex.Message}");
flag = true;
}
return flag;
}
Đây là code to test the acquire lock.
static void Main(string[] args) {
string lockKey = "lock:eat";
TimeSpan expiration = TimeSpan.FromSeconds(5);
// 5 person eat something...
Parallel.For(0, 5, x => {
string person = $"person:{x}";
bool isLocked = AcquireLock(lockKey, person, expiration);
if (isLocked) {
Console.WriteLine($"{person} begin eat food (with lock) at {DateTimeOffset.Now.ToUnixTimeMilliseconds()}.");
} else {
Console.WriteLine($"{person} cannot eat food due to not getting the lock.");
}
});
Console.WriteLine("end");
Console.Read();
}
Sau khi chạy code, chúng ta may get the following result.

Only one person can get the lock! Others are waiting.
Mặc dù lock sẽ automatically removed by Redis, nó cũng does not make good use of the shared resource!
Bởi vì khi một process finishes its job, nó should let others use the resource, not wait endlessly!
Vì vậy chúng ta also need to release the lock as well.
How To Release A Lock?
Để release the lock, chúng ta just removed the item in Redis!
Về những gì chúng ta take in creating a lock, chúng ta need to match the unique value of the resource. This will make it safer to release the right lock.
Khi matching, chúng ta will delete the lock, which means that the unlock was successful. Otherwise, the unlock was unsuccessful.
Chúng ta need to execute the get and del commands at a time, so we will use a Lua script to do this!
/// <summary>
/// Releases the lock.
/// </summary>
/// <returns><c>true</c>, if lock was released, <c>false</c> otherwise.</returns>
/// <param name="key">Key.</param>
/// <param name="value">Value.</param>
static bool ReleaseLock(string key, string value) {
string lua_script = @"
if (redis.call('GET', KEYS[1]) == ARGV[1]) then
redis.call('DEL', KEYS[1])
return true
else
return false
end
";
try {
var res = Connection.GetDatabase().ScriptEvaluate(lua_script, new RedisKey[] { key }, new RedisValue[] { value });
return (bool)res;
} catch (Exception ex) {
Console.WriteLine($"ReleaseLock lock fail...{ex.Message}");
return false;
}
}
Chúng ta should call this method khi một process has finished.
Khi một process gets the lock và does not release the lock vì some reason, other processes cannot wait until it is released. At this time, other processes should go ahead.
Đây là sample to deal with this scene.
Parallel.For(0, 5, x => {
string person = $"person:{x}";
var val = 0;
bool isLocked = AcquireLock(lockKey, person, expiration);
while (!isLocked && val <= 5000) {
val += 250;
System.Threading.Thread.Sleep(250);
isLocked = AcquireLock(lockKey, person, expiration);
}
if (isLocked) {
Console.WriteLine($"{person} begin eat food (with lock) at {DateTimeOffset.Now.ToUnixTimeMilliseconds()}.");
if (new Random().NextDouble() < 0.6) {
Console.WriteLine($"{person} release lock {ReleaseLock(lockKey, person)} {DateTimeOffset.Now.ToUnixTimeMilliseconds()}");
} else {
Console.WriteLine($"{person} do not release lock ....");
}
} else {
Console.WriteLine($"{person} begin eat food (without lock) at {DateTimeOffset.Now.ToUnixTimeMilliseconds()}.");
}
});
Sau khi chạy sample, you may get the following result.
As you can see, persons 3 and 4 will go ahead without a lock.
Đây là source code bạn có thể find on my GitHub page.
- RedisLockDemo
Tóm tắt
Bài viết này introduced how to create distributed locks with Redis in .NET Core. And it's a basic version, you can improve based on your business.
Tôi hy vọng this helps you.