首页 > 技术文章 > Python-Redis-发布订阅

xiao-xue-di 2019-07-30 13:54 原文

参考博客:http://www.runoob.com/redis/redis-pub-sub.html

一、前言

  Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息。

  Redis 客户端可以订阅任意数量的频道。

  下图展示了频道 channel1 , 以及订阅这个频道的三个客户端 —— client2 、 client5 和 client1 之间的关系:

  

  当有新消息通过 PUBLISH 命令发送给频道 channel1 时, 这个消息就会被发送给订阅它的三个客户端:

  

二、事例

 Demo: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import redis
 
 
class RedisHelper:
 
    def __init__(self):
        self.__conn = redis.Redis(host='172.16.200.49')
        self.chan_sub = 'fm104.5'
        self.chan_pub = 'fm104.5'
 
    def public(self, msg):
        self.__conn.publish(self.chan_pub, msg)
        return True
 
    def subscribe(self):
        pub = self.__conn.pubsub()
        pub.subscribe(self.chan_sub)
        pub.parse_response()
        return pub

  订阅者:

1
2
3
4
5
6
7
8
9
10
# -*- coding: UTF-8 -*-
 
from redis_helper import RedisHelper
 
obj = RedisHelper()
redis_sub = obj.subscribe()
 
while True:
    msg = redis_sub.parse_response()
    print(msg)

  发布者:

1
2
3
4
5
6
7
8
# -*- coding: UTF-8 -*-
 
from redis_helper import RedisHelper
 
obj = RedisHelper()
while True:
    msg = input('>>:')
    obj.public(msg)

  

 
 

推荐阅读