python redis用戶端使用lua指令碼

來源:互聯網
上載者:User

標籤: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指令碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.