MST
星途 面试题库

面试题:Python中Redis数据库订阅与发布功能的基础实现

请使用Python和Redis库实现一个简单的订阅与发布系统,其中包括一个发布者,向名为 'test_channel' 的频道发送消息 'Hello, Redis Pub/Sub!',以及一个订阅者,能接收并打印该频道的消息。
26.6万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import redis

# 发布者
def publisher():
    r = redis.Redis(host='localhost', port=6379, db=0)
    r.publish('test_channel', 'Hello, Redis Pub/Sub!')

# 订阅者
def subscriber():
    r = redis.Redis(host='localhost', port=6379, db=0)
    p = r.pubsub()
    p.subscribe('test_channel')
    for message in p.listen():
        if message['type'] =='message':
            print(message['data'].decode('utf-8'))
        elif message['type'] == 'psubscribe':
            continue
        else:
            break


if __name__ == '__main__':
    from threading import Thread
    pub_thread = Thread(target=publisher)
    sub_thread = Thread(target=subscriber)
    pub_thread.start()
    sub_thread.start()
    pub_thread.join()
    sub_thread.join()