Language/Javascript, typescript
[Typescript] 로컬 저장소에 대한 Lock 구현
junha6316
2022. 10. 21. 11:16
레디스 같은 저장소가 아닌 로컬에서 구현할 때 동시성 이슈를 막기 위해 lock을 구현해야할 때가 있다. 자바스크립트 패키지중 하나인 await-lock을 이용해 add나 update에 대해서 lock을 걸어 동시성이슈를 막을 수 있다.
https://www.npmjs.com/package/await-lock
await-lock
Mutex locks for async functions. Latest version: 2.2.2, last published: 6 months ago. Start using await-lock in your project by running `npm i await-lock`. There are 127 other projects in the npm registry using await-lock.
www.npmjs.com
import AwaitLock from 'await-lock';
export class LocalRepositoryService {
private _state = new Map<number, any>(); // 저장소
private _lock: AwaitLock;
constructor() {
this._lock = new AwaitLock(); // initialize 될 때 lock 생성
}
public async get(
id: number,
options: GetOptions = { lock: false },
): Promise<any> {
const user = this._state.get(id);
return user;
}
public async add(user: any) {
await this._lock.acquireAsync(); // lock 획득
try {
this._userState.set(user.id, user);
return true;
} catch (error) {
console.log(error);
return false;
} finally {
this._lock.release(); // 종료시 lock 반환
}
}
}