【脚本语言系列】关于Python实现网络模式发布-订阅,你需要知道的事

时间:2022-06-17 22:59:16

如何使用发布-订阅

Redis

# -*- coding:utf-8 -*-
import redis
import random
# publish
conn = redis.Redis()
sports = ["adidas","nike","reebok","fila"]
shirts = ["only","orchily","esprit","muji"]
for msg in range(10):
sport = random.choice(sports)
shirt = random.choice(shirts)
print ("Publish: %s and %s" %(sport, shirt))
conn.publish(sport, shirt)
# -*- coding:utf-8 -*-
import redis
# subscribe
conn = redis.Redis()
topics = ["nike", "orchily"]
sub = conn.pubsub()
sub.subscribe(topics)
for msg in sub.listen():
if msg["type"] == "message":
sport = msg["channel"]
shirt = msg["data"]
print ("Subscribe: %s and a %s" %(sport, shirt))

ZeroMQ

# -*- coding:utf-8 -*-
import zmq
import random
import time
# publish
host = "*"
port = 6789
ctx = zmq.Context()
pub = ctx.socket(zmq.PUB)
pub.bind("tcp://%s:%s" %(host, port))
sports = ["adidas","nike","reebok","fila"]
shirts = ["only","orchily","esprit","muji"]
time.sleep(1)
for msg in range(10):
sport = random.choice(sports)
sport_bytes = sport.encode("utf-8")
shirt = random.choice(shirts)
shirt_bytes = shirt.encode("utf-8")
print ("Publish: %s and %s" %(sport, shirt))
pub.send_multipart([sport_bytes,shirt_bytes])
# -*- coding:utf-8 -*-
import zmq
# subscribe
host = "127.0.0.1"
port = 6789
ctx = zmq.Context()
sub = ctx.socket(zmq.SUB)
sub.connect("tcp://%s:%s" %(host, port))
topics = ["nike", "orchily"]
for topic in topics:
sub.setsockopt(zmq.SUBSCRIBE, topic.encode("utf-8"))
while True:
sport_bytes, shirt_bytes = sub.recv_multipart()
sport = sport_bytes.decode("utf-8")
shirt = shirt_bytes.decode("utf-8")
print ("Subscribe: %s and %s" %(sport, shirt))

RabbitMQ/pika

pypubsub

pubsubhubbub

什么是发布-订阅

发布-订阅:简单的发布-订阅系统中,所有订阅者都会受到发布者发送的信息副本;
订阅者只关心特定类型的数据,发布者只会发送这些数据。