In Redis pubsub, is it possible to pass an object to the PUBLISH command?
Redis has no meaning of "objects", all redis gets are bytes, specifically strings!
So when you want to publish an object you have to serialize it some way and deserialize it on the subscriber.
Yes, but because redis stores strings rather than objects, you'll need to serialize/unserialize objects as part of the PUBLISH process. JSON is an ideal format for this.
This question has been asked a long time ago, however, if anyone gets here, this worked for me using the nodejs redis library.
npm i redis
The easiest way if you are using node.js is to simply publish like this:
const data = {
name: 'John Doe',
age: 0
};
publisher.publish('<channel_name>', JSON.stringify(data));
The client subscriber can then read using the following code:
subscriber.on('message', (channel, message) => {
const data = JSON.parse(message);
console.log(data);
// your code goes here to do whatever you want with the data
});
subscriber.subscribe('<channel_name>');
Result:
{name: 'John Doe', age: 0}