python redis客户端使用lua脚本,redislua,有一个需求,为一个k


有一个需求,为一个key设置一个field存储时间戳,每当有新数据,判断新数据时间戳是否>之前的时间戳,如果是,更新时间戳,由于依赖中间执行结果,所以使用lua减少客户端和服务端通信次数
#!/usr/bin/python# -*- coding: utf-8 -*-import redisr = 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 redislocal timestamp_old = redis.call(‘hget‘, key, field)
-- if timestamp_old == nil, it means the key is not existif 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, 也可以指定其为pipelineprint res

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

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

python redis客户端使用lua脚本

评论关闭