import redis
import time
import threading
import json
发布 JSON 数据
data = {
'name': 'Alice',
'age': 25,
'city': 'New York'
}
json_string = json.dumps(data)
连接到 Redis 服务器
r = redis.StrictRedis(host='localhost', port=6379, db=0)
使用 set 和 get 方法
r.set('mykey', 'Hello Redis!')
value = r.get('mykey')
print(value.decode('utf-8'))
发布者示例
def publisher():
time.sleep(1)
r.publish('channel', json_string)
订阅者示例
def subscriber():
pubsub = r.pubsub()
pubsub.subscribe('channel')
for item in pubsub.listen():
if item['type'] == 'message':
print(item['data'].decode('utf-8'))
break
启动发布者和订阅者线程
publisher_thread = threading.Thread(target=publisher)
subscriber_thread = threading.Thread(target=subscriber)
publisher_thread.start()
subscriber_thread.start()
publisher_thread.join()
subscriber_thread.join()