Listen for changes in Redis?

node.js, redis

Solution

You can also connect to the Redis server like a follower using the sync command. See How Redis Replication Works? for a quick introduction.

The output of sync command has two phases. In the first phase, the server returns the database dump.rdb file. Once the file is sent, it starts sending commands in the Redis protocol, which is also the AOF format.

Here is the high level picture of what you can do :

- Connect to the Redis server and issue the `SYNC` command

- Save and parse the dump.rdb file. Build the initial data set. A node.js based rdb parser is available

- Parse the commands that follow. Since they are in Redis protocol, you can start with an existing Redis library.

- For every command you receive, invoke a callback

It seems a lot of work, but you should be able to hack this pretty easily. And it would make a good open source library too!

EDIT : Sync v/s Monitor

- `Monitor` is a debugging command. The response format can (and has) change(d) over time. `Sync` is used for Master -> Slave replication, and so will be better supported

- `Monitor` will emit all commands, including read-only commands. `Sync` will only get you commands that modify data.

- `Monitor` will log individual commands that are executed within a lua script. `Sync` will only transfer the entire lua script, so you will have to parse the script yourself. This is indeed a deal breaker for `sync`.

- `Monitor` will log commands that did not succeed, `Sync` will only log commands that modify data. For example, the command `del non-existing-key` will be logged by monitor but won't show up when you run sync.

Problem

I want to be able to run a callback when any change is made in my redis collection. The callback would take the key and value as inputs. Is something like this possible? Thanks?

Original source