一.阻塞
import redis
class RedisBloking():
"""
阻塞发布订阅
"""
def __init__(self):
self.__conn = redis.Redis(host='127.0.0.1', port=6379)
self.channel = 'long_channel'
def publish(self, msg):
"""
发布消息
:param msg:
:return:
"""
self.__conn.publish(self.channel, msg)
return True
def subscribe(self):
"""
订阅消息
:return:
"""
pub = self.__conn.pubsub()
pub.subscribe(self.channel)
pub.parse_response()
return pub
redis_obj = RedisBloking()
redis_obj.publish("发不了一条消息")
meg_obj = redis_obj.subscribe()
message = meg_obj.parse_response()
二.非阻塞
import redis
class RedisNonBlocking():
"""
非阻塞发布订阅
"""
def __init__(self, channelname):
self.__conn = redis.Redis(host='127.0.0.1', port=6379)
self.key = channelname
def queue_size(self):
"""
返回队列中的消息数量
:return:
"""
return self.__conn.llen(self.key)
def put_msg(self, msg):
"""
发布消息
:param msg:
:return:
"""
self.__conn.rpush(self.key, msg)
def getmsg_wait(self, timeout=1):
"""
订阅消息,设置等待时间
:param timeout: 默认1秒钟等待
:return:
"""
return self.__conn.blpop(self.key, timeout=timeout)
def getmsg_nowait(self):
"""
订阅消息,不等待,没有消息返回None
:return:
"""
return self.__conn.lpop(self.key)
redis_obj = RedisNonBlocking('long_channel')
redis_obj.put_msg("发布一条消息")
redis_obj.getmsg_wait(timeout=10)
三.参考资料
发布订阅
https://www.cnblogs.com/kellynic/p/9952386.html
redis功能
https://www.cnblogs.com/melonjiang/p/5342383.html
redis数据接口操作
https://www.cnblogs.com/melonjiang/p/5342505.html