Reputation: 21368
.Net Core and IDistributedCache with Redis (https://learn.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-3.1). How does one perform atomic operations when using IDistributedCache with Redis? I want to make sure I do not overwrite any values in cache if many different users connect to two different endpoints and run redisCache.Set() command at the same time.
Upvotes: 1
Views: 2418
Reputation: 21368
I found this useful and it seems to do what I want: https://redis.io/topics/distlock, more specifically: https://github.com/samcook/RedLock.net
Registration:
services.AddSingleton<IDistributedLockFactory, RedLockFactory>(x =>
RedLockFactory.Create(new List<RedLockEndPoint> { new DnsEndPoint(options.Host, options.Port) }));
Usage:
public RedisCache(IDistributedCache cache, IDistributedLockFactory lockFactory)
{
_cache = cache;
_lockFactory = lockFactory;
}
public async Task<T> GetOrAddAsync(string key, Func<T> createItem)
{
...
using (var redLock = await _lockFactory.CreateLockAsync(key, _expire, _wait, _retry))
{
if (redLock.IsAcquired)
{
// do stuff here
_cache.Set(.....);
}
}
return cacheEntry;
}
Upvotes: 5