zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Python的七大数据类型整理
    Linux下获取线程ID tid的方法
    字符串逆序操作
    ftp的两种模式
    exec函数族
    代码行数统计(指定目录下所有文件的Line)
    windows 命令行操作
    C语言时间打印
    Anaconda下载安装说明
    python 使用request进行get post请求
  • 原文地址:https://www.cnblogs.com/buxizhizhoum/p/9295981.html
Copyright © 2011-2022 走看看