Skip to content

Instantly share code, notes, and snippets.

@n4nagappan
Created December 13, 2019 09:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n4nagappan/3506403c90189d0144327f29a08aa30c to your computer and use it in GitHub Desktop.
Save n4nagappan/3506403c90189d0144327f29a08aa30c to your computer and use it in GitHub Desktop.
Redis Key expiry notification
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