The EDirectInsure Distributed Lock module.
npm install @edirect/lockThe EDirectInsure Distributed Lock module.
Distributed lock module for Edirect applications. Provides cluster-safe locking mechanisms using Redis, supporting both timed and distributed locks for critical section management.
- Distributed locking using Redis
- Timed locks for exclusive task execution
- Integrates with NestJS and Edirect config modules
``bash`
npm install @edirect/lock
Import and register LockModule in your AppModule:
`typescript
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 {}
`
`typescript`
lock(key: string, callback: (unlock: () => void) => void, ttl?: number): void
`typescript`
set(key: string, value: string, override = false): Promise
get(key: string): Promise
/**
`typescript`
getLockOwner(): Promise
setLockOwner(): Promise
removeLockOwner(): Promise
isLockOwner(): Promise
For example, the usage of the Distributed Lock:
`typescript`
if (await this.lockService.isLockOwner()) {
// Logic that should run on only one cluster
}
And for the Timed Lock:
`typescript
this.lockService.lock('locked-task-name', async unlock => {
// Logic that should be executed in exclusivity, across all instances
unlock();
});
`
- REDIS_HOST: Redis server hostREDIS_PORT
- : Redis server portREDIS_PASS
- : Redis password (if required)NAMESPACE`: Lock owner namespace
-