1. 程式人生 > >Redis儲存結構之釋出/訂閱

Redis儲存結構之釋出/訂閱

Redis儲存結構之訂閱。

 

PSUBSCRIBE
PUBLISH
PUBSUB
PUNSUBSCRIBE
SUBSCRIBE
UNSUBSCRIBE

 

該模式與訊息佇列的區別在與可以多客戶端同時訂閱。

import _thread
import logging
import random
import time

import redis

client = redis.Redis(host='127.0.0.1', port=6379, db=0, decode_responses=True)
topic = 'pub-sub'


def sub():
    _pub = client.pubsub()
    _pub.subscribe(topic)
    while True:
        _resp = _pub.parse_response()
        logging.info(_resp[2])


def pub_and_sub():
    # no.1
    _thread.start_new_thread(sub, ())
    # no.2
    _thread.start_new_thread(sub, ())
    # start to publish
    for i in range(0, 100):
        n = random.random() * 1.5
        time.sleep(n)
        logging.info('No.%s: %s', i, n)
        client.publish(topic, n)


if __name__ == '__main__':
    pub_and_sub()