需求:
从redis的字典A中查找获取结果a,将结果a作为条件查找字典B获取结果b,再将b添加到字典C中,将字典B中的记录b删除。保证整个过程的原子性。
查询redis的官方文档,给上述需求中的代码过程加入事务,在redis中用multi和exec即可实现,multi:开启事务,exec:结束事务。
方案一(卒):查询python client中的redispy,发现pipeline内封装了multi和exec,可以将需要保持原子性的代码置于管道之间,如下:
import redis
r = redis.Redis(host=“localhost”,
port=6379,
db=1,
decode_responses=True)
# 开启pipeline的事务
pipe = r.pipeline(transaction=True)
pipe.multi()
key = pipe.spop('test_set02')
print(key)
value = pipe.hget('test_hash01',key)
print(value)
pipe.hset('test_hash02',key,value)
pipe.hdel('test_hash01',key)
pipe.execute()
控制台打印结果报错如下:
redis.exceptions.DataError: Invalid input of type: 'Pipeline'. Convert to a bytes, string, int or float first.
打印结果如下:
走过的弯路和解决方案如上,希望能给遇到同样问题的你给予帮助,祝好。
因为管道是批量处理以上的命令,所以中间返回的结果不是真正存在redis中的数据,方案一卒。
方案二:
redis的lua脚本默认支持代码的原子性,遂即转战lua脚本,方案可行,代码如下:
import redis
r = redis.Redis(host="localhost",
port=6379,
db=1,
decode_responses=True)
cmd = r.register_script(
"""
local set_id = redis.pcall('spop',KEYS[1])
if set_id == "nil" then
return set_id
end
local updated_at = redis.pcall('hget',KEYS[2],set_id)
redis.pcall('hset',KEYS[3],set_id,updated_at)
redis.pcall('hdel',KEYS[2],set_id)
return set_id
"""
)
result= cmd(keys = ["test_set01","test_hash01","test_hash02"])
print(result)
走过的弯路和解决方案如上,希望能给遇到同样问题的你给予帮助,祝好。