【问题标题】:Is there any way to insert some python statement when using python redis transaction?使用python redis事务时有什么方法可以插入一些python语句?
【发布时间】:2018-08-29 19:08:43
【问题描述】:

Redis 在 python 中非常容易使用。但是,现在我在使用 Redis 事务时遇到了问题。首先,我要在Redis中得到一个key,接下来我要检查这个key绑定的值是否合法。我希望这些操作是原子的。这是我的代码。

pipe = redis_conn.pipeline()
pipe.multi()
var = pipe.get('key_want_to_be_read')
if is_legal(val):
    do_something
else:
    do_another_thing
pipe.execute()

但是,当我运行这些代码时,python名称var并没有绑定到存储在redis中的值,而是Pipeline<ConnectionPool<Connection<host=localhost,port=6379,db=0>>>,所以。有没有办法在redis事务中获取密钥并将其绑定到python名称?

【问题讨论】:

  • 您应该使用WATCH 命令或Lua 脚本来完成这项工作。以this 为例。

标签: python redis


【解决方案1】:

你可以像这样注册一个lua脚本:

import redis
r = redis.StrictRedis(host='localhost', port=6379, db=0)
redis_script = r.register_script("""
    local valueToTest = redis.call('GET','{key}')
    --Test key in lua
    """.format(key=key_to_be_read))

然后用redis_script()调用它

来自Redis site,这是原子的:

Redis 使用相同的 Lua 解释器来运行所有命令。还 Redis 保证脚本以原子方式执行:没有其他 脚本或 Redis 命令将在脚本运行时执行 执行。

【讨论】:

    猜你喜欢
    • 2012-11-04
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多