How to use publish-subscribe
Redis
#-*-Coding:utf-8-*-
import redis
import random
# publish
conn = Redis. Redis ()
sports = ["Adidas", "Li-Ning", "Reebok", "Fila"]
shirts = ["Only", "orchily", "Esprit", "Muji"] for
msg In range:
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 = ["Li-Ning", "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-*-import zmq import time # Random host = "*" Port = Publish 6789 = Zmq. Context () pub = Ctx.socket (zmq. PUB) Pub.bind ("tcp://%s:%s"% (host, port)) sports = ["Adidas", "Li-Ning", "Reebok", "fila"] shirts = ["Only", "orchily", "" Esprit "," Muji "] time.sleep (1) for MSG in range: 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, S Hirt)) 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 = ["Li-Ning", "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
What is publish-subscribe
Publish-Subscribe: Simple publish-subscribe system, all Subscribers will be sent by the publisher copy of the information;
Subscribers only care about specific types of data, and publishers only send that data.