python+redis的发布订阅功能

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()

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值