| | | 1 | | using Intentum.Distributed.Locking; |
| | | 2 | | using StackExchange.Redis; |
| | | 3 | | |
| | | 4 | | namespace Intentum.Distributed.Redis; |
| | | 5 | | |
| | | 6 | | public sealed class RedisDistributedLock : IDistributedLock |
| | | 7 | | { |
| | | 8 | | private readonly IDatabase _db; |
| | | 9 | | private readonly string _keyPrefix; |
| | | 10 | | |
| | 0 | 11 | | public RedisDistributedLock(IConnectionMultiplexer connection, string keyPrefix = "intentum:lock:") |
| | 0 | 12 | | { |
| | 0 | 13 | | _db = connection.GetDatabase(); |
| | 0 | 14 | | _keyPrefix = keyPrefix; |
| | 0 | 15 | | } |
| | | 16 | | |
| | | 17 | | public async Task<bool> AcquireAsync(string key, TimeSpan timeout, CancellationToken cancellationToken = default) |
| | 0 | 18 | | { |
| | 0 | 19 | | var redisKey = $"{_keyPrefix}{key}"; |
| | 0 | 20 | | var token = Environment.MachineName + Guid.NewGuid().ToString("N"); |
| | 0 | 21 | | return await _db.LockTakeAsync(redisKey, token, timeout); |
| | 0 | 22 | | } |
| | | 23 | | |
| | | 24 | | public async Task ReleaseAsync(string key, CancellationToken cancellationToken = default) |
| | 0 | 25 | | { |
| | 0 | 26 | | var redisKey = $"{_keyPrefix}{key}"; |
| | 0 | 27 | | await _db.KeyDeleteAsync(redisKey); |
| | 0 | 28 | | } |
| | | 29 | | } |