【指令碼語言系列】關於Python實現網路模式發布-訂閱,你需要知道的事__Python

來源:互聯網
上載者:User
如何使用發布-訂閱 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 什麼是發布-訂閱

發布-訂閱:簡單的發布-訂閱系統中,所有訂閱者都會受到發行者發送的資訊副本;
訂閱者只關心特定類型的資料,發行者只會發送這些資料。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.