开发者

In Redis pubsub, is it possible to pass an object to the PUBLISH command?

I have an application which inserts record to a postgresql table 开发者_运维知识库and after the insert, I want to send a PUBLISH command to redis. Is it possible to pass an object of that record to redis' PUBLISH command so the subscriber on the other end will receive the object too?


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}


For python developers. Serialize python dict using json.dumps().

Publisher

import json 

payload_dict = {
 'key1':'value1',
 'key2':'value2'
}

data = json.dumps(payload_dict)
publisher.publish('channel', data)

Subscriber

 data = subscriber.get('data').decode('utf-8')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜