赞
踩
昨天小程为大家更新了使用redis直接连接然后实现的发布订阅,今天为大家带来使用redis连接池实现的reids发布订阅模式,下面直接给大家上代码不废话
import redis
from redis import ConnectionPool
class RedisPoolPu:
def __init__(self):
self.redis_conn = self.get_redis_conn
@property
def get_redis_conn(self):
redis_pool = ConnectionPool(host='101.43.29.136', port=6379, max_connections=10)
redis_conn = redis.Redis(connection_pool=redis_pool)
return redis_conn
def handle_message(self, message):
print('Received message:', message)
def redis_rub(self):
p = self.redis_conn.pubsub()
# p.psubscribe('channel:*')
p.subscribe(**{'channel:1': self.handle_message, 'channel:2': self.handle_message})
for message in p.listen():
print(message)
if __name__ == '__main__':
RedisPoolPu().redis_rub()
import redis
from redis import ConnectionPool
# def __init__(self, host='101.43.29.136', port=6379):
class RedisPoolPu:
def __init__(self):
self.redis_conn = self.get_redis_conn
@property
def get_redis_conn(self):
redis_pool = ConnectionPool(host='101.43.29.136', port=6379, max_connections=10)
redis_conn = redis.Redis(connection_pool=redis_pool)
return redis_conn
def publish_message(self, channel, message):
self.redis_conn.publish(channel, message)
def redis_publish(self):
# 发布消息到频道 channel:1
self.publish_message('channel:1', 'Hello, Redis!')
# 发布消息到频道 channel:2
self.publish_message('channel:2', '你好呀')
if __name__ == '__main__':
RedisPoolPu().redis_publish()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。