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

如何使用发布-订阅

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

什么是发布-订阅

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值