python開發——實現redis中的發布訂閱功能
redis中的發布/訂閱模型是一種消費通訊模式,下面將對這一功能進行python**的實現。
from redis import strictredis
class
redishelper
(object):
''' 封裝redis發布訂閱類 '''
def__init__
(self)
: self.conn = strictredis(host=
'localhost'
, port=
6379
) self.sub_chanle =
'books'
defpublish
(self, msg)
:''' 發布訊息'''
self.conn.publish(self.sub_chanle, msg)
defsubscribe
(self)
:''' 獲取訊息'''
pub = self.conn.pubsub(
) pub.subscribe(self.sub_chanle)
return pub
from pubsub import redishelper
obj = redishelper(
)for i in
range(5
):obj.publish(f'hello_'
)
from pubsub import redishelper
obj = redishelper(
)sub = obj.subscribe(
)while
true
: msg = sub.listen(
)for i in msg:
if i[
'type']==
'message'
:print
(str
(i['channel'
], encoding=
'utf-8')+
':'+
str(i[
'data'
], encoding=
'utf-8'))
elif i[
'type']==
'subscribe'
:print
(str
(i['channel'
], encoding=
'utf-8'
))
Redis發布訂閱模式實現
redisutil工具類 public class redisutil 發布訊息 public static void publish string channel,string message 訂閱訊息 public static void subscribe jedispubsub jedisp...
Redis發布訂閱模式
publish subscribe 發布訂閱模式的原理 包含兩個角色,乙個是發布者,乙個是訂閱者 訂閱者可以訂閱乙個或者多個頻道channel 發布者可以向指定頻道發布資訊 通過publish發布訊息 publish channel message publish channel1.1 maizie...
redis訂閱發布模式
理論遲點再補,先上 直接上 demopub.php 發布者 redis new redis redis connect localhost 6379 redis publish mcs 麒麟之才 demosub.php 訂閱者 redis new redis redis connect 127.0....