项目作者: ch1seL

项目描述 :
Simple async-await distributed lock service based on Redis
高级语言: C#
项目地址: git://github.com/ch1seL/DistributedLock.git
创建时间: 2020-10-25T09:08:37Z
项目社区:https://github.com/ch1seL/DistributedLock

开源协议:MIT License

下载


Build and Test

This package is just RedLock.net wrapper and simplifies it using within NetCore

Usage

Run redis server on you machine first

docker run -d -p 6379:6379 redis

Add ch1seL.DistributedLock.RedisLock to your project

dotnet add package ch1seL.DistributedLock.RedisLock

Register in DI

  1. Host.CreateDefaultBuilder(args)
  2. .ConfigureServices((hostContext, services) =>
  3. {
  4. services.AddStackExchangeRedisLock(options => options.Configuration = "localhost");
  5. }

Inject and lock some piece of code

  1. public class Worker : BackgroundService
  2. {
  3. private readonly IDistributedLock _distributedLock;
  4. public Worker(IDistributedLock distributedLock)
  5. {
  6. _distributedLock = distributedLock;
  7. }
  8. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  9. {
  10. using (await _distributedLock.CreateLockAsync("test-lock", cancellationToken: stoppingToken)) {
  11. await DoSomeStuff();
  12. }
  13. }
  14. }

Testing and local usage

For testing or local usage you can register in-memory implementation

dotnet add package ch1seL.DistributedLock.MemoryLock

  1. Host.CreateDefaultBuilder(args)
  2. .ConfigureServices((hostContext, services) => {
  3. if (hostContext.HostingEnvironment.IsDevelopment()) {
  4. services.AddMemoryLock();
  5. } else {
  6. services.AddStackExchangeRedisLock(options => options.Configuration = "localhost");
  7. }
  8. }

Sample

https://github.com/ch1seL/DistributedLock/tree/master/samples/WorkerService