-
Notifications
You must be signed in to change notification settings - Fork 335
Add true retriever lock #314
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
499ef6e
Fix typo
carlamendozadominguez 0a69a40
Merge pull request #301 from carlamendozadominguez/patch-1
catcherwong b2f49c9
Merge pull request #310 from dotnetcore/dev
catcherwong f130340
Add true retriever lock
pengweiqhca d80bcf9
Add true retriever lock
pengweiqhca b812ce3
Use DistributedLock
pengweiqhca 56893f9
Fix get with dataRetriever bug
pengweiqhca 3d4b6f6
Fix test fail
pengweiqhca 3daf4f6
Fix test fail
pengweiqhca 11dbf5d
static => instance
pengweiqhca f8af20d
Increase SleepMs
pengweiqhca 0a69334
Fix test fail
pengweiqhca 2d02aa7
Add true retriever lock
pengweiqhca cc76dba
fix test fail
pengweiqhca c3bd563
Each cache uses its own lock Factory
pengweiqhca File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
22 changes: 22 additions & 0 deletions
22
src/EasyCaching.CSRedis/DistributedLock/CSRedisLockFactory.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| using EasyCaching.Core.DistributedLock; | ||
| using Microsoft.Extensions.Logging; | ||
| using Microsoft.Extensions.Options; | ||
| using System.Collections.Generic; | ||
| using System.Linq; | ||
|
|
||
| namespace EasyCaching.CSRedis.DistributedLock | ||
| { | ||
| public class CSRedisLockFactory : DistributedLockFactory | ||
| { | ||
| private readonly IEnumerable<EasyCachingCSRedisClient> _clients; | ||
|
|
||
| public CSRedisLockFactory(IEnumerable<EasyCachingCSRedisClient> clients, | ||
| IOptionsMonitor<RedisOptions> optionsMonitor, | ||
| ILoggerFactory loggerFactory = null) | ||
| : base(name => DistributedLockOptions.FromProviderOptions(optionsMonitor.Get(name)), loggerFactory) => | ||
| _clients = clients; | ||
|
|
||
| protected override IDistributedLockProvider GetLockProvider(string name) => | ||
| new CSRedisLockProvider(name, _clients.Single(x => x.Name.Equals(name))); | ||
| } | ||
| } |
42 changes: 42 additions & 0 deletions
42
src/EasyCaching.CSRedis/DistributedLock/CSRedisLockProvider.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| using CSRedis; | ||
| using EasyCaching.Core.DistributedLock; | ||
| using System; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace EasyCaching.CSRedis.DistributedLock | ||
| { | ||
| public class CSRedisLockProvider : IDistributedLockProvider | ||
| { | ||
| private readonly string _name; | ||
| private readonly EasyCachingCSRedisClient _database; | ||
|
|
||
| public CSRedisLockProvider(string name, EasyCachingCSRedisClient database) | ||
| { | ||
| _name = name; | ||
| _database = database; | ||
| } | ||
|
|
||
| public Task<bool> SetAsync(string key, byte[] value, int ttlMs) => | ||
| _database.SetAsync($"{_name}/{key}", value, TimeSpan.FromMilliseconds(ttlMs)); | ||
|
|
||
| public bool Add(string key, byte[] value, int ttlMs) => | ||
| _database.Set($"{_name}/{key}", value, TimeSpan.FromMilliseconds(ttlMs), RedisExistence.Nx); | ||
|
|
||
| public Task<bool> AddAsync(string key, byte[] value, int ttlMs) => | ||
| _database.SetAsync($"{_name}/{key}", value, TimeSpan.FromMilliseconds(ttlMs), RedisExistence.Nx); | ||
|
|
||
| public bool Delete(string key, byte[] value) => | ||
| (long)_database.Eval(@"if redis.call('GET', KEYS[1]) == ARGV[1] then | ||
| return redis.call('DEL', KEYS[1]); | ||
| end | ||
| return -1;", $"{_name}/{key}", value) >= 0; | ||
|
|
||
| public async Task<bool> DeleteAsync(string key, byte[] value) => | ||
| (long)await _database.EvalAsync(@"if redis.call('GET', KEYS[1]) == ARGV[1] then | ||
| return redis.call('DEL', KEYS[1]); | ||
| end | ||
| return -1;", $"{_name}/{key}", value) >= 0; | ||
|
|
||
| public bool CanRetry(Exception ex) => ex is RedisClientException; | ||
| } | ||
| } | ||
187 changes: 187 additions & 0 deletions
187
src/EasyCaching.Core/DistributedLock/DistributedLock.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,187 @@ | ||
| using Microsoft.Extensions.Logging; | ||
| using System; | ||
| using System.Diagnostics; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace EasyCaching.Core.DistributedLock | ||
| { | ||
| public class DistributedLock : MemoryLock | ||
| { | ||
| private readonly IDistributedLockProvider _provider; | ||
| private readonly object _syncObj = new object(); | ||
| private readonly DistributedLockOptions _options; | ||
| private readonly ILogger _logger; | ||
|
|
||
| private byte[] _value; | ||
| private Timer _timer; | ||
|
|
||
| public DistributedLock(string name, string key, IDistributedLockProvider provider, DistributedLockOptions options, ILoggerFactory loggerFactory = null) : base($"{name}/{key}") | ||
| { | ||
| _provider = provider; | ||
| _options = options; | ||
| _logger = loggerFactory?.CreateLogger(GetType().FullName); | ||
| } | ||
|
|
||
| public override bool Lock(int millisecondsTimeout, CancellationToken cancellationToken) | ||
| { | ||
| var sw = Stopwatch.StartNew(); | ||
| if (base.Lock(millisecondsTimeout, cancellationToken)) | ||
| { | ||
| GetNewGuid(); | ||
|
|
||
| do | ||
| { | ||
| try | ||
| { | ||
| if (_provider.Add(Key, _value, _options.MaxTtl)) | ||
| { | ||
| StartPing(); | ||
|
|
||
| return true; | ||
| } | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| _logger?.LogWarning(default, ex, ex.Message); | ||
|
|
||
| if (!_provider.CanRetry(ex)) break; | ||
| } | ||
|
|
||
| if (cancellationToken.IsCancellationRequested) | ||
| { | ||
| _value = null; | ||
|
|
||
| cancellationToken.ThrowIfCancellationRequested(); | ||
| } | ||
|
|
||
| Thread.Sleep(Math.Max(0, Math.Min(100, millisecondsTimeout - (int)sw.ElapsedMilliseconds))); | ||
| } while (sw.ElapsedMilliseconds < millisecondsTimeout); | ||
|
|
||
| _logger?.LogWarning($"{Key}/Wait fail"); | ||
|
|
||
| base.Release(); | ||
| } | ||
|
|
||
| _value = null; | ||
| return false; | ||
| } | ||
|
|
||
| public override async ValueTask<bool> LockAsync(int millisecondsTimeout, CancellationToken cancellationToken) | ||
| { | ||
| var sw = Stopwatch.StartNew(); | ||
| if (await base.LockAsync(millisecondsTimeout, cancellationToken)) | ||
| { | ||
| GetNewGuid(); | ||
|
|
||
| do | ||
| { | ||
| try | ||
| { | ||
| if (await _provider.AddAsync(Key, _value, _options.MaxTtl)) | ||
| { | ||
| StartPing(); | ||
|
|
||
| return true; | ||
| } | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| _logger?.LogWarning(default, ex, ex.Message); | ||
|
|
||
| if (!_provider.CanRetry(ex)) break; | ||
| } | ||
|
|
||
| if (cancellationToken.IsCancellationRequested) | ||
| { | ||
| _value = null; | ||
|
|
||
| cancellationToken.ThrowIfCancellationRequested(); | ||
| } | ||
|
|
||
| await Task.Delay(Math.Max(0, Math.Min(100, millisecondsTimeout - (int)sw.ElapsedMilliseconds)), cancellationToken); | ||
| } while (sw.ElapsedMilliseconds < millisecondsTimeout); | ||
|
|
||
| _logger?.LogWarning($"{Key}/Wait fail"); | ||
|
|
||
| await base.ReleaseAsync(); | ||
| } | ||
|
|
||
| _value = null; | ||
| return false; | ||
| } | ||
|
|
||
| public override void Release() | ||
| { | ||
| Interlocked.Exchange(ref _timer, null)?.Dispose(); | ||
|
|
||
| var value = Interlocked.Exchange(ref _value, null); | ||
| if (value == null) return; | ||
|
|
||
| try | ||
| { | ||
| if (_provider.Delete(Key, value)) _logger?.LogInformation($"{Key}/Release lock"); | ||
| else _logger?.LogWarning($"{Key}/Release lock fail"); | ||
| } | ||
| finally | ||
| { | ||
| base.Release(); | ||
| } | ||
| } | ||
|
|
||
| public override async ValueTask ReleaseAsync() | ||
| { | ||
| Interlocked.Exchange(ref _timer, null)?.Dispose(); | ||
|
|
||
| var value = Interlocked.Exchange(ref _value, null); | ||
| if (value == null) return; | ||
|
|
||
| try | ||
| { | ||
| if (await _provider.DeleteAsync(Key, value)) _logger?.LogInformation($"{Key}/Release lock"); | ||
| else _logger?.LogWarning($"{Key}/Release lock fail"); | ||
| } | ||
| finally | ||
| { | ||
| await base.ReleaseAsync(); | ||
| } | ||
| } | ||
|
|
||
| private void GetNewGuid() | ||
| { | ||
| lock (_syncObj) | ||
| { | ||
| if (_value != null) throw new DistributedLockException(); | ||
|
|
||
| var id = Guid.NewGuid(); | ||
|
|
||
| _value = id.ToByteArray(); | ||
|
|
||
| _logger?.LogDebug($"{Key}/NewGuid: {id:D}"); | ||
| } | ||
| } | ||
|
|
||
| private void StartPing() | ||
| { | ||
| _logger?.LogInformation($"{Key}/Wait success, start ping"); | ||
|
|
||
| _timer = new Timer(Ping, this, _options.DueTime, _options.Period); | ||
| } | ||
|
|
||
| private static async void Ping(object state) | ||
| { | ||
| var self = (DistributedLock)state; | ||
|
|
||
| try | ||
| { | ||
| await self._provider.SetAsync(self.Key, self._value, self._options.MaxTtl); | ||
|
|
||
| self._logger?.LogDebug($"{self.Key}/Ping success"); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| self._logger?.LogWarning(default, ex, $"{self.Key}/Ping fail"); | ||
| } | ||
| } | ||
| } | ||
| } |
12 changes: 12 additions & 0 deletions
12
src/EasyCaching.Core/DistributedLock/DistributedLockException.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| using System; | ||
|
|
||
| namespace EasyCaching.Core.DistributedLock | ||
| { | ||
| [Serializable] | ||
| public class DistributedLockException : Exception | ||
| { | ||
| public DistributedLockException() : base("锁释放前请不要重复锁") { } | ||
|
|
||
| public DistributedLockException(string message) : base(message) { } | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What about move the lua script to a constant?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
https://redis.io/topics/distlock