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

「Redis学习笔记」事务和错误处理

2015-09-30 16:26 671 查看
1.事务执行单元

127.0.0.1:6379> multi
OK
127.0.0.1:6379> sadd "user:1:folloing" 2
QUEUED
127.0.0.1:6379> sadd "user:2:followers" 1
QUEUED
127.0.0.1:6379> exec
1) (integer) 1
2) (integer) 1


2.错误处理

a.语法错误

127.0.0.1:6379> multi
OK
127.0.0.1:6379> set key value
QUEUED
127.0.0.1:6379> set key
(error) ERR wrong number of arguments for 'set' command
127.0.0.1:6379> errorcommand key
(error) ERR unknown command 'errorcommand'
127.0.0.1:6379> exec
(error) EXECABORT Transaction discarded because of previous errors.
127.0.0.1:6379> get key
"\xe7\x88\xb1"


b.执行时出错

127.0.0.1:6379> multi
(error) ERR MULTI calls can not be nested
127.0.0.1:6379> set key 1
QUEUED
127.0.0.1:6379> sadd key 2
QUEUED
127.0.0.1:6379> set key 3
QUEUED
127.0.0.1:6379> exec
(error) EXECABORT Transaction discarded because of previous errors.
127.0.0.1:6379> get key
"\xe7\x88\xb1"
Redis 的事务没有关系数据库事务提供的回滚(rollback)功能。为此开发者必须在事务执行出错后自己收拾剩下的摊子(将数据库复原会事务执行前的状态)

3.Watch

127.0.0.1:6379> set key 1
OK
127.0.0.1:6379> watch key
OK
127.0.0.1:6379> set key 2
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set key 3
QUEUED
127.0.0.1:6379> exec
(nil)
127.0.0.1:6379> get key
"2"
watch 命令可以监控一个或多个键,一旦其中有一个键被修改(或删除),之后的事务就不会执行

执行exec命令后会取消对所有键的监控,如果不想执行事务中的命令,也可以使用unwatch命令来取消监控。比如,我们要实现hsetxx函数,作用与hsetnx命令类似,只不过仅当字段存在时才赋值。为了避免竞态条件,我们使用事务来完成这一功能:

def incr($key)
watch $key
$value = get $key
if not $value
$value = 0
$value = $value + 1
multi
set $key, $value
result = exec
return result[0]

# 使用unwatch
def hsetxx($key, $field, $value)
watch $key
$isFieldExists = hexists $key, $field
if $isFieldExists is 1
multi
hset $key, $field, $value
exec
else
unwatch
return $isFieldExists
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: