I want to implement RedisLock usning StackExchange.Redis library.
By following this article:
https://www.c-sharpcorner.com/article/creating-distributed-lock-with-redis-in-net-core/
- How do I need to block a Redis stream.
- How do I need to unlock Redis stream. Do I really need to use a script to remove an object from a stream, maybe another programm want to handle current element?
Problem with runing script, but every pass of the loop the programm can't realise the lock but next pass is able to get access to locked stream:
My implementation:
Implementation of RedisLock the same as in article.
public async void ListenTask()
{
var handledResult = await db.StreamRangeAsync(streamName, "-", "+", 1, Order.Descending);
var lowestHandledId = handledResult.Last().Id;
var readTask = Task.Run(async () =>
{
while (!Token.IsCancellationRequested)
{
var result = await db.StreamRangeAsync(streamName, lowestHandledId, "+", 2);
var handleResult = result.Last();
if (result.Any() && lowestHandledId != handleResult.Id)
{
bool isLocked = RedisLock.AcquireLock(streamName, handleResult.Id.ToString(), expiry);
if (!isLocked)
{
//lock
lowestHandledId = handleResult.Id;
var streamCat = handleResult.Values;
Cat cat = ParseResult(streamCat);
switch (streamCat[0].Value.ToString())
{
case "insert":
Console.WriteLine($"Insert cat at id:{cat.Id} [{cat.Name} - {cat.CreatedDate}]");
cacheDictionary.Add(cat.Id, new WeakReference(cat));
break;
case "delete":
Console.WriteLine($"Deleted cat at id:{cat.Id}");
cacheDictionary.Remove(cat.Id);
break;
}
RedisLock.ReleaseLock(streamName, handleResult.Id.ToString());
}
}
await Task.Delay(2000);
}
});
}