发布-订阅模型

#发布者,
import redis
import random
conn=redis.Redis()
cats=['siamese','persian','maine coon','norwegian forest']
hats=['stovepipe','bowler','tam-o-shanter','fedora']
for msg in range(10):
    cat=random.choice(cats)
    hat=random.choice(hats)
    print('Publish: %s wears a %s'%(cat,hat))
    conn.publish(cat,hat)

输出:
Publish: siamese wears a tam-o-shanter
Publish: norwegian forest wears a bowler
Publish: norwegian forest wears a bowler
Publish: maine coon wears a stovepipe
Publish: maine coon wears a fedora
Publish: siamese wears a tam-o-shanter
Publish: maine coon wears a tam-o-shanter
Publish: norwegian forest wears a fedora
Publish: persian wears a stovepipe
Publish: siamese wears a bowler

#订阅者
import redis
conn=redis.Redis()
topics=['maine coon','persian']#只订阅这两个品种
sub=conn.pubsub()
sub.subscribe(topics)
for msg in sub.listen():#listen方法会返回一个字典
    if msg['type']=='message':
        cat=msg['channel']#话题
        hat=msg['data']#消息的值
        print('Subscribe: %s wears a %s'%(cat,hat))

输出:
Subscribe: b’maine coon’ wears a b’stovepipe’
Subscribe: b’maine coon’ wears a b’fedora’
Subscribe: b’maine coon’ wears a b’tam-o-shanter’
Subscribe: b’persian’ wears a b’stovepipe’

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值