python redis客户端使用lua脚本

有一个需求,为一个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

猜你喜欢

转载自www.cnblogs.com/buxizhizhoum/p/9295981.html