简体   繁体   中英

how to get notifiction if any changes/transaction happen in redis using nodejs

I'am new to redis, i need help to get notify to my running server if any chages/transaction happen in redis(either from bakend also). The server which is in running state is created using node.js

Use the keyspace notification system. This uses the pub sub layer of redis

Steps : Set this parameter -notify-keyspace-events in redis.conf file By default its empty

This will enable capture of almost all DML events

I'm not sure about how to get notification about transaction, but here is a working code (using ioredis ) to get notified about any change in redis:

const redisClient = const redisClient = new Redis({
    host: 'localhost',
    port: 20000,
    lazyConnect: true, // because i will try to connect manually in the next line
    connectTimeout: 1000,
  })
await redisClient.connect()

// "AKE" === listen to all events of all redis-operations
await redisClient.config('SET', 'notify-keyspace-events', 'AKE')
await redisClient.psubscribe([`__key*__:*`])

redisClient.on(`pmessage`, (_pattern, redisKey, redisOpeation) => {
   const redisKey = redisKey.replace('__keyspace@0__:', '')
   if(redisKey === 'cool-redis-key' && redisOpeation === 'set'){
      console.log(`there was a "set" operation on "cool-redis-key" key`)
   }
})

Addtional info:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM