解决Redis Cluster模式下键空间通知Keyspace notification失效的
解决Redis Cluster模式下键空间通知Keyspace notification失效的问题(python实现)
在做一个支付订单的CASE,需要对订单进行限定时间内支付,到期未完成支付则该订单失效,商品退库处理。
这种案例很适合使用redis的keyspace notification键空间通知功能
键空间通知使得客户端可以通过订阅频道或模式, 来接收那些以某种方式改动了 Redis 数据集的事件。
可以通过对redis的redis.conf文件中配置notify-keyspace-events参数可以指定服务器发送哪种类型的通知。下面对于一些参数的描述。默认情况下此功能是关闭的。
字符
通知
K
键空间通知,所有通知以 [email protected] 为前缀
E
键事件通知,所有通知以 [email protected] 为前缀
g
DEL 、 EXPIRE 、 RENAME 等类型无关的通用命令的通知
$
字符串命令的通知
l
列表命令的通知
s
集合命令的通知
h
哈希命令的通知
z
有序集合命令的通知
x
过期事件:每当有过期键被删除时发送
e
驱逐(evict)事件:每当有键因为 maxmemory 政策而被删除时发送
A
参数 g$lshzxe 的别名
所以当你配置文件中配置为AKE时就表示发送所有类型的通知。
也可以直接通过命令行设置:
redis-cli config set notify-keyspace-events KEA
先来看redis普通模式(单机/主从),引用网络上的一段实例代码1:
# subcribe.py
from redis import StrictRedis
# 连接redis数据库
redis = StrictRedis(host='localhost', port=6379, decode_responses=True)
# 创建pubsub对象,该对象订阅一个频道并侦听新消息:
pubsub = redis.pubsub()
# 定义触发事件
def event_handler(msg):
print('Handler', msg)
print(msg['data'])
order_id = str(msg['data'])
# 获取订单对象
order = OrderInfo.objects.get(order_id=order_id)
# 判断用户是否已经付款
if str(order.status) == "1":
# 取消订单,更改订单状态
OrderInfo.objects.filter(order_id=order_id).update(status="6")
# 获取订单中的所有商品
goods = order.skus.all()
# 遍历商品
for good in goods:
# 获取订单中的商品数量
count = good.count
print(count)
# 获取sku商品
sku = good.sku
# 将库存重新增加到sku的stock中去
sku.stock += count
# 从销量中减去已经取消的数量
sku.sales -= count
sku.save()
#订阅redis键空间通知
pubsub.psubscribe(**{'[email protected]__:expired': event_handler})
# 死循环,不停的接收订阅的通知
while True: