#发布者,
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’