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, password='your-password', 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()

 

你可能感兴趣的:(Python,Redis,MQ,Case)