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

来源:互联网 发布:apache jsonobject 编辑:程序博客网 时间:2024/06/15 06:03

1.事务执行单元

127.0.0.1:6379> multiOK127.0.0.1:6379> sadd "user:1:folloing" 2QUEUED127.0.0.1:6379> sadd "user:2:followers" 1QUEUED127.0.0.1:6379> exec1) (integer) 12) (integer) 1

2.错误处理

a.语法错误

127.0.0.1:6379> multiOK127.0.0.1:6379> set key valueQUEUED127.0.0.1:6379> set key(error) ERR wrong number of arguments for 'set' command127.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 nested127.0.0.1:6379> set key 1QUEUED127.0.0.1:6379> sadd key 2QUEUED127.0.0.1:6379> set key 3QUEUED127.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 1OK127.0.0.1:6379> watch key OK127.0.0.1:6379> set key 2OK127.0.0.1:6379> multiOK127.0.0.1:6379> set key 3QUEUED127.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



0 0
原创粉丝点击