您的位置:首页 > 数据库 > Redis

redis事务

2015-07-23 19:41 537 查看
一、REDIS事务

REDIS的事务很简单,只支持关系型数据库事务中ACID中的CID,即不支持原子性

事务中有失败的操作也不会回滚整个事务,而是继续执行后面的命令

二、事务举例

在一个终端里开启事务后,做如下操作

127.0.0.1:7379> set foo "test trans"
OK
127.0.0.1:7379> multi
OK
127.0.0.1:7379> set foo "set 123"
QUEUED
127.0.0.1:7379> incr foo
QUEUED
127.0.0.1:7379> exec
1) OK
2) (error) ERR value is not an integer or out of range


在没有执行exec前,从另一个终端里看到的结果依然还是事务前的结果

127.0.0.1:7379> get foo
"test trans"


执行了exec后

可以看到两条返回结果,其中事务里的第二条命令执行失败了

但是并不影响事务里其它命令的执行结果

127.0.0.1:7379> get foo
"set 123"


从另一个终端的查询结果看,foo的内容已经被修改

另外,如果事务命令队列中间的某个命令发生了异常,也不会影响后面命令的执行

三、为什么不支持回滚

官方是这样给出的理由

Why Redis does not support roll backs?
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 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.


四、watch命令

按照官方给出的描述,这个命令是给一些需要保持原子性操作的场景做的补充

在事务开启前,通过watch命令监控某些key,当在多线程环境下,发生了争抢,key的值被修改后,后执行的事务会收到失败状态码,以提示使用者事务失败

从使用场景上来说,我目前没发现我需要有这样的场景

另外从安全角度来说,redis对事务原子性支持不好,那就不要用了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: