Redis 的Pub(Publish)和Sub(Subscribe)即发布订阅功能。Pub/Sub是采用比较广泛的通信模型。采用事件作为通信机制,提供松散耦合的交互模式。
ps订阅方法:
subscribe - 订阅一个或多个频道
psubscribe - 订阅pattern匹配的频道(如:temppub* 订阅temppub开头的频道)

redis_pub.py发布demo

python
1
2
3
4
5
6
7
8
9
10
# -*- coding=utf-8 -*-
import json

import redis

redis_con_pool = redis.ConnectionPool(host='127.0.0.1', port=6379, decode_responses=True, db=0)
redis_con = redis.Redis(connection_pool=redis_con_pool)

redis_con.publish("temppub2", json.dumps({"test": "hhh2"}))
redis_con.publish("temppub1", json.dumps({"test": "hhh"}))

redis_sub.py

python
1
2
3
4
5
6
7
8
9
10
11
12
13
# -*- coding=utf-8 -*-
import redis

redis_con_pool = redis.ConnectionPool(host='127.0.0.1', port=6379, decode_responses=True, db=0)
redis_con = redis.Redis(connection_pool=redis_con_pool)

ps = redis_con.pubsub()
ps.subscribe(["temppub1", "temppub2"])
# ps.psubscribe('temppub*') # pattern模式,订阅全部temppub开头的频道

for item in ps.listen():
if item["type"] == "message": # 如果使用psubscribe此处type为pmessage
print(item["data"])