標籤:rip script line class [1] 指定 print 判斷 oca
有一個需求,為一個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指令碼