python + redis 实现简单的消息订阅
订阅端
import redis
from functools import wraps
class Subscribe:
def __init__(self, channel: str, **kwargs):
self.coon = redis.StrictRedis(**kwargs)
self.channel = channel
self.registerd = list()
self.course = self.coon.pubsub()
self.course.subscribe(self.channel)
def register(self, func):
self.registerd.append(func)
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def listen(self):
messages = self.course.listen()
for message in messages:
self.dispatch(message)
def dispatch(self, message):
for handler in self.registerd:
handler(message)
DEFAULT_CHANNEL = 'channle'
subscribe = Subscribe(DEFAULT_CHANNEL)
@subscribe.register
def print_args(message):
print(message)
subscribe.listen()
- 先创建一个订阅对象,利用register装饰器来注册监听到的消息的处理函数
- 最后执行listen方法来监听,当当前对象监听到了消息,会自动转交给所有的处理函数
发布端
import redis
coon = redis.StrictRedis()
coon.publish('channel', '发布的消息对象')