首页 > 编程语言 > 详细

python redis客户端使用lua脚本

时间:2018-07-11 18:49:34      阅读:203      评论:0      收藏:0      [点我收藏+]
有一个需求,为一个key设置一个field存储时间戳,每当有新数据,判断新数据时间戳是否>之前的时间戳,如果是,更新时间戳,由于依赖中间执行结果,所以使用lua减少客户端和服务端通信次数
#!/usr/bin/python
# -*- coding: utf-8 -*-
import redis

r = redis.Redis("127.0.0.1")

lua = """
local key = KEYS[1]
local field = ARGV[1]
local timestamp_new = ARGV[2]

-- get timestamp of the key in redis local timestamp_old = redis.call(‘hget‘, key, field)
-- if timestamp_old == nil, it means the key is not exist if timestamp_old == nil or timestamp_new > timestamp_old then redis.call(‘hset‘, key, field, timestamp_new) end
""" cmd = r.register_script(lua) res = cmd(keys=[meterdata_36118_plab_current], args=[time, 1533299183]) # 关键字参数client可以设置执行lua脚本的client instance, 也可以指定其为pipeline print res

使用pipeline的watch也可以获取pipeline执行期间的结果,但是在获取结果期间还是和服务端进行了通信,增加了网络消耗。

lua脚本也可以放在pipe执行,只需指定client=pipeline

python redis客户端使用lua脚本

原文:https://www.cnblogs.com/buxizhizhoum/p/9295981.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!