如何使用發布-訂閱
Redis
# -*- coding:utf-8 -*-import redisimport random# publishconn = 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# subscribeconn = 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 zmqimport randomimport time# publishhost = "*"port = 6789ctx = 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# subscribehost = "127.0.0.1"port = 6789ctx = 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
什麼是發布-訂閱
發布-訂閱:簡單的發布-訂閱系統中,所有訂閱者都會受到發行者發送的資訊副本;
訂閱者只關心特定類型的資料,發行者只會發送這些資料。