简短截说阐述redis中事务(Redis Transactions)的使用

简短截说阐述redis中事务(Redis Transactions)的使用
    我们知道,在关系型数据库中,比如mysql,如果要使用事务,首先向数据库服务器发送 BEGIN ,然后执行各个相互一致的写操作和读操作,最后,用户可以选择发送 COMMIT 来确认之前所做的修改,或者发送 ROLLBACK 来放弃那些修改。

    同样, Redis 中也有简单的方法处理一连串相互一致的读操作和写操作。首先是以 MULTI 命令开始事务,后续跟着一连串命令,最后以 EXEC 结束事务或者以 DISCARD 命令撤销所有命令并结束事务。

    

    但是redis事务和mysql事务最重要的一点区别是,redis事务不管指令正确或者错误,都会执行,中途遇见错误指令也会继续执行后面的指令,Redis并没有像mysql那样的事务回滚机制。mysql事务中如果执行过程中发生了错误不仅后面的sql语句不会执行,还会进行数据回滚,这是二者事务的最大区别。Redis的事务出错需要开发人员自己进行数据回滚等操作。


    在翻阅了redis官方手册以后,官方对此的解释是:If you have a relational databases background, the fact that Redis commands can fail during a transaction, but still Redis will execute the rest of the transaction instead of rolling back, may look odd to you. However there are good opinions for this behavior:
Redis commands can fail only if called with a wrong syntax (and the problem is not detectable during the command queueing), or against keys holding the wrong data type: this means that in practical terms a failing command is the result of a programming errors, and a kind of error that is very likely to be detected during development, and not in production.
Redis is internally simplified and faster because it does not need the ability to roll back.
An argument against Redis point of view is that bugs happen, however it should be noted that in general the roll back does not save you from programming errors. For instance if a query increments a key by 2 instead of 1, or increments the wrong key, there is no way for a rollback mechanism to help. Given that no one can save the programmer from his or her errors, and that the kind of errors required for a Redis command to fail are unlikely to enter in production, we selected the simpler and faster approach of not supporting roll backs on errors.

    大白话的意思就是:redis的作者认为,当事务的执行时,一般发生错误都是因为业务编程错误造成的,这种错误通常只会出现在开发环境中,而基本很少会在实际的生产环境中出现(因为这种业务错误都会在测试的时候消灭),所以他认为没有必要为 Redis 开发事务自动回滚功能,这和Redis追求的简单高效的设计主旨不符合。

    

    而mysql恰恰相反,mysql认为数据库有必要也有责任处理事务中报错的情况,所以mysql有自动回滚的功能。


    在redis中使用事务:

    

liuyue:~ liuyue$ redis-cli
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set test 123
QUEUED
127.0.0.1:6379> exec
1) OK
127.0.0.1:6379> get test
"123"
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set test 456
QUEUED
127.0.0.1:6379> discard
OK
127.0.0.1:6379> get test
"123"
127.0.0.1:6379> 
liuyue:~ liuyue$ clear
在python中操作redis事务
#导包
import redis

#定义ip
host = 'localhost'

#建立服务连接

r = redis.Redis(host=host)
pipe = r.pipeline()

#开启事务
pipe.multi()
#存储子命令
pipe.set('key2', 4)
#执行事务
pipe.execute()

print(r.get('key2'))


相关视频: