@edirect/lock
v11.0.43
Published
The EDirectInsure Distributed Lock module.
Maintainers
Keywords
Readme
@edirect/lock
The EDirectInsure Distributed Lock module.
@edirect/lock
Distributed lock module for Edirect applications. Provides cluster-safe locking mechanisms using Redis, supporting both timed and distributed locks for critical section management.
Features
- Distributed locking using Redis
- Timed locks for exclusive task execution
- Integrates with NestJS and Edirect config modules
Installation
npm install @edirect/lockUsage
Import and register LockModule in your AppModule:
import { ConfigService } from '@edirect/config';
@Module({
imports: [
LockModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
lockOwner: configService.get(Variables.NAMESPACE),
redis: {
host: configService.get(Variables.REDIS_HOST),
password: configService.get(Variables.REDIS_PASS),
port: +configService.get(Variables.REDIS_PORT),
},
}),
inject: [ConfigService],
}),
],
})
export class AppModule {}API
Timed Lock
lock(key: string, callback: (unlock: () => void) => void, ttl?: number): voidRedis Values
set(key: string, value: string, override = false): Promise<void>
get(key: string): Promise<string>
/**Distributed Lock
getLockOwner(): Promise<string>
setLockOwner(): Promise<string>
removeLockOwner(): Promise<void>
isLockOwner(): Promise<boolean>For example, the usage of the Distributed Lock:
if (await this.lockService.isLockOwner()) {
// Logic that should run on only one cluster
}And for the Timed Lock:
this.lockService.lock('locked-task-name', async unlock => {
// Logic that should be executed in exclusivity, across all instances
unlock();
});Environment Variables
REDIS_HOST: Redis server hostREDIS_PORT: Redis server portREDIS_PASS: Redis password (if required)NAMESPACE: Lock owner namespace
