install

npm install nestjs-simple-redis-lock

Module注册

import { Module } from '@nestjs/common';
import { RedisLockModule } from 'nestjs-simple-redis-lock';

@Module({
    imports: [
        RedisLockModule.register({
            clientName: 'myredis', // RedisModule模块注册的时候的名称
            prefix: 'myredis_service_redis_lock:',
        }),
    ],
    providers: [],
})
export class MyCustomModule { }

使用

https://github.com/hanFengSan/nestjs-simple-redis-lock

import { RedisLockService, RedisLock } from 'nestjs-simple-redis-lock';

export class FooService {
  constructor(
    protected readonly lockService: RedisLockService, // inject RedisLockService 
  ) {}

  /**
   * Wrap the method, starting with getting a lock, ending with unlocking
   * The first parameter is lock name
   * By default, automatically unlock after 1min.
   * By default, try again after 100ms if failed
   * By default, the max times to retry is 600, about 1min
   */
  @RedisLock('test2')
  async test1() {
    // Do somethings
    return 'some values';
  }

  /**
   * Automatically unlock after 2min
   * Try again after 50ms if failed
   * The max times to retry is 100
   */ 
  @RedisLock('test2', 2 * 60 * 1000, 50, 100)
  async test2() {
    // Do somethings
    return 'some values';
  }
}