Created
December 13, 2019 09:26
-
-
Save n4nagappan/3506403c90189d0144327f29a08aa30c to your computer and use it in GitHub Desktop.
Redis Key expiry notification
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export namespace RedisExpiryNotification { | |
const callbackMap: any = {} | |
const PREFIX = '__keyspace@?__:' | |
redisClient.send_command( | |
'config', | |
// ['set', 'notify-keyspace-events', 'Ex'], | |
['set', 'notify-keyspace-events', 'Kx'], | |
RedisExpiryNotification.onRedisKeyExpiredCallback | |
) | |
redisClient.on('pmessage', onRedisKeyExpiredCallback) | |
export function onExpiry(key: string, callback: () => void) { | |
log.info('Subscribing to expiry updates on', key) | |
if (!(key in callbackMap)) { | |
callbackMap[key] = [] | |
} | |
callbackMap[key].push(callback) | |
const expired_subKey = `${PREFIX}${key}` | |
redisClient.psubscribe(expired_subKey) | |
} | |
export function onRedisKeyExpiredCallback( | |
chan: string, | |
pattern: string, | |
event: string | |
) { | |
const key = pattern.substring(PREFIX.length) | |
if (key in callbackMap) { | |
const callbacks = callbackMap[key] | |
callbacks.forEach((cb: any) => { | |
cb(null) | |
}) | |
delete callbackMap[key] | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment