redis的发布订阅是指发布者将消息发布到redis的某个频道中,然后监听了该频道的客户端就会收到相应的推送信息.
redis连接:
import redis
方式1:
# 创建连接池
pool = redis.ConnectionPool(host=host, port=port, db=db, password=passwd)
con = redis.Redis(connection_pool=pool)
方式2:
con = redis.Redis(host=host, port=port, db=db, password=passwd)
方式3:
# 通过url连接
url = "redis://:passwd@ip:port/db"
con = red.form_url(url)
# 或
pool = redis.ConnectionPool.from_url(url)
发布者:
# 发送hello world消息到mes频道中 ,函数执行将返回一个整形数据,表示当前有多少客户端在监听此频道
con.publish("mes", "hello world")
订阅者:
sub = con.pubsub()
阻塞监听:
sub.psubscribe(["mes"])
for item in sub.lsten():
# 阻塞监听,channel为频道名称, data为接收的内容,初次监听时,会有一个测试数据
print(item["channel"], item["data"])
非阻塞监听:
sub.psubscribe(["mes"])
while True:
item = sub.get_message()
if item:
# 有监听到数据
print(item["channel"], item["data"])
time.sleep(0.3)
线程非阻塞监听:
def my_handle(item):
print(item["channel"], item["data"])
sub = con.subscribe(*{"mes":my_handle})
th = sub.run_in_thread(0.03)
# 开始监听后,若要停止,可执行如下语句
th.stop()