Redis事务是一组命令的集合,可以一次性执行多个命令,并保证这些命令的原子性。在执行事务期间,Redis不会中断事务,而是将事务中的命令缓存起来,直到事务提交时才一次性执行。
Python操作Redis事务可以使用Redis的pipeline
对象。pipeline
对象允许将多个命令打包成一个事务,并一次性发送给Redis服务器执行。
import redis
pool = redis.ConnectionPool(host='192.168.10.8', port=6379, password='120099', decode_responses=True)
r = redis.Redis(connection_pool=pool)
def transaction_test():
# 操作事务
try:
pipe = r.pipeline(transaction=True) # transaction默认为True(默认开启事务)
pipe.multi() # 开启事务
pipe.set("username", "zhangshang")
pipe.sadd('students', 'student_a', 'student_b', 'student_c')
# 管道命令可以写道一起
#pipe.set("username", "zhangshang").sadd('students', 'student_a', 'student_b', 'student_c')
# a = 1 / 0 # 异常
pipe.execute() # 提交事务
except Exception as e:
print(e)
pipe.reset() # 回滚事务
transaction_test()
在上面的示例中,首先从连接池中获取了一个Redis
对象,然后使用pipeline
方法创建了一个pipeline
对象。接下来,使用pipeline
对象的set和sadd
方法添加了两个命令到事务中。最后,使用execute
方法执行事务,当遇到异常时会进行回滚。
需要注意的是,事务中的命令并不会立即执行,而是缓存在本地,直到调用execute
方法时才一次性发送给Redis服务器执行。因此,在事务执行之前,可以随时添加、修改或删除事务中的命令。
此外,还可以使用watch
方法在事务执行之前监视某个或某些键,当这些键被其他客户端修改时,事务会被打断