Files
ZYZ/game-server/app/services/redlockCacheService.ts
2021-03-04 20:36:59 +08:00

46 lines
1.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { fromCallback } from 'bluebird';
import { scheduleJob } from 'node-schedule';
import { nowSeconds } from '../pubUtils/timeUtil';
import { RedlockService } from '../services/redLockService';
interface UserCache {
time: number;
lock: any;
}
var userCacheMap = new Map<string, UserCache>();
export function init() {
scheduleJob('clearDirtyData', "0/5 * * * * *", clearDirtyData);//每个5秒钟释放redis锁
}
/**
* 释放锁
*/
export function clearDirtyData() {
userCacheMap.forEach(function(userCache, key) {
if(nowSeconds() > userCache.time + 10){
console.log('show lock =' + JSON.stringify(userCache.lock));
releaseLock(key);
}
})
}
/**
* 根据key解锁
* @param lockKey
*/
export function releaseLock(lockKey: string) {
var userCache = userCacheMap.get(lockKey);
if (!!userCache && userCache.lock){
// unlock your resource when you are done
userCache.lock.unlock();
}
userCacheMap.delete(lockKey);
}
export function setLock(lockKey: string, lock: any){
userCacheMap.set(lockKey, {lock, time: nowSeconds()})
};
export function getLock(lockKey: string) {
var userCache = userCacheMap.get(lockKey);
return !!userCache && !!userCache.lock
}