python achieve Redis subscriptions to the publication

Redis publish and subscribe

Redis can be used as publish-subscribe message notification, group chat, directional push, refresh load parameters and other business scenarios

Publish and subscribe model has three roles:

  1. Publisher (Publisher)
  2. Subscribers (Subscriber)
  3. Channel (channel)

Each subscriber can subscribe to multiple channels, publishers can post messages on a channel, the subscriber will receive a message in their own subscription channel released.

1. Related command ( Reference )

publish channel message         发布消息
subscribe [channel]             订阅频道
unsubscribe [channel]           取消订阅
psubscribe [pattern...]         订阅指定模式的频道
punsubscribe [pattern...]       退订指定模式的频道
pubsub channels                 列出至少有一个订阅者的频道
pubsub numsub [channel...]      列表给定频道的订阅者数量
pubsub numpat                   列表被订阅模式的数量 

Example of use of the terminal

# 在 终端1 订阅cctv1
127.0.0.1:8100> subscribe cctv1
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "cctv1"
3) (integer) 1
# 在 终端2 向cctv1 发布消息
127.0.0.1:8100> publish cctv1 "this is cctv1"
(integer) 1
# 终端1 接受到终端2发的消息
127.0.0.1:8100> subscribe cctv1
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "cctv1"
3) (integer) 1
1) "message"
2) "cctv1"
3) "this is cctv1"

2. python achieve

from PublishAndSubscribe.Channel import Channel
from PublishAndSubscribe.RedisTool import RedisTool


class Subscriber:
    def __init__(self, conn):
        self._conn = conn

    def subscribe(self, channel: Channel):
        # 获取发布/订阅对象
        pub = self._conn.pubsub()
        # 选择要订阅的频道
        pub.subscribe(channel.name)
        while True:
            # 接收消息
            msg = pub.parse_response()
            print(msg)


if __name__ == '__main__':
    client = RedisTool.redis_connection("0.0.0.0", 8100, "password")
    cctv1 = Channel("CCTV1")
    Subscriber(client).subscribe(cctv1)

from PublishAndSubscribe.Channel import Channel
from PublishAndSubscribe.RedisTool import RedisTool


class Publisher:
    def __init__(self, conn):
        self._conn = conn

    def publish(self, channel: Channel, mess: str):
        # 向特定频道发布消息
        self._conn.publish(channel.name, mess)


if __name__ == '__main__':
    cctv1 = Channel("CCTV1")
    client = RedisTool.redis_connection("0.0.0.0", 8100, "password")
    publisher = Publisher(client)
    while True:
        publisher.publish(cctv1, input("请输入要发送的消息:"))

class Channel:
    def __init__(self, name: str):
        self.name = name
import redis


class RedisTool:
    @staticmethod
    def redis_connection(address: str, port: int, password: str):
        """
        用来连接Redis
        Args:
            address: Redis 服务端IP地址
            port: [int] Redis 服务端口
            password: Redis client 登录凭证
        Return:
            type[Redis]: 返回一个redis对象
        """
        return redis.StrictRedis(address, port, password=password)
  • For simplicity in subscribers and publishers are two examples of a "CCTV1" channel, there will be no problem (simply by distinguishing channel Redis string in), although with them, but in practice this should be the same object.

result:
Here Insert Picture Description

Published 63 original articles · won praise 33 · views 10000 +

Guess you like

Origin blog.csdn.net/zjbyough/article/details/104401553