127.0.0.1:6379> MULTI OK 127.0.0.1:6379> set name xiaoming QUEUED 127.0.0.1:6379> set age 20 QUEUED 127.0.0.1:6379> set address city QUEUED 127.0.0.1:6379> set email xiaoming@qq.com QUEUED 127.0.0.1:6379> EXEC 1) OK 2) OK 3) OK 4) OK 127.0.0.1:6379> keys * 1) "address" 2) "name" 3) "email" 4) "age" 127.0.0.1:6379> mget name age address email 1) "xiaoming" 2) "20" 3) "city" 4) "xiaoming@qq.com" 127.0.0.1:6379>
3.3,情况2:放弃事务
1 2 3 4 5 6 7 8 9 10 11 12 13 14
127.0.0.1:6379> MULTI OK 127.0.0.1:6379> INCR age QUEUED 127.0.0.1:6379> set address "city location" QUEUED 127.0.0.1:6379> DISCARD OK 127.0.0.1:6379> mget name age address email 1) "xiaoming" 2) "20" 3) "city" 4) "xiaoming@qq.com" 127.0.0.1:6379>
127.0.0.1:6379> MULTI OK 127.0.0.1:6379> INCR age QUEUED 127.0.0.1:6379> set address "city location" QUEUED 127.0.0.1:6379> mget name age address email QUEUED 127.0.0.1:6379> get name QUEUED 127.0.0.1:6379> set score (error) ERR wrong number of arguments for 'set' command 127.0.0.1:6379> set email xiaoming123@qq.com QUEUED 127.0.0.1:6379> EXEC (error) EXECABORT Transaction discarded because of previous errors. 127.0.0.1:6379> 127.0.0.1:6379> keys * 1) "address" 2) "name" 3) "email" 4) "age" 127.0.0.1:6379> mget name age address email 1) "xiaoming" 2) "20" 3) "city" 4) "xiaoming@qq.com" 127.0.0.1:6379>
127.0.0.1:6379> MULTI OK 127.0.0.1:6379> INCR age QUEUED 127.0.0.1:6379> set address "city location" QUEUED 127.0.0.1:6379> mget name age address email QUEUED 127.0.0.1:6379> get name QUEUED 127.0.0.1:6379> INCR email QUEUED 127.0.0.1:6379> set score 100 QUEUED 127.0.0.1:6379> EXEC 1) (integer) 21 2) OK 3) 1) "xiaoming" 2) "21" 3) "city location" 4) "xiaoming@qq.com" 4) "xiaoming" 5) (error) ERR value is not an integer or out of range 6) OK 127.0.0.1:6379> 127.0.0.1:6379> keys * 1) "name" 2) "email" 3) "score" 4) "address" 5) "age" 127.0.0.1:6379> mget name age address email score 1) "xiaoming" 2) "21" 3) "city location" 4) "xiaoming@qq.com" 5) "100" 127.0.0.1:6379>
3.6,情况5:watch监控
3.6.1,悲观锁/乐观锁
(1) 悲观锁(Pessimistic Lock), 顾名思义,就是很悲观,每次去拿数据的时候都认为别人会修改,所以每次在拿数据的时候都会上锁,这样别人想拿这个数据就会block直到它拿到锁。传统的关系型数据库里边就用到了很多这种锁机制,比如行锁,表锁等,读锁,写锁等,都是在做操作之前先上锁,例如: select * from sys_user for update
127.0.0.1:6379> mget balance debt 1) "70" 2) "30" 127.0.0.1:6379> watch debt OK 127.0.0.1:6379> set debt 50 OK 127.0.0.1:6379> MULTI OK 127.0.0.1:6379> DECRBY balance 30 QUEUED 127.0.0.1:6379> INCRBY debt 30 QUEUED 127.0.0.1:6379> EXEC (nil) 127.0.0.1:6379> mget balance debt 1) "70" 2) "50" 127.0.0.1:6379>
3.6.3,unwatch
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
127.0.0.1:6379> WATCH balance OK 127.0.0.1:6379> set balance 300 OK 127.0.0.1:6379> UNWATCH OK 127.0.0.1:6379> MULTI OK 127.0.0.1:6379> set balance 100 QUEUED 127.0.0.1:6379> set debt 0 QUEUED 127.0.0.1:6379> EXEC 1) OK 2) OK 127.0.0.1:6379> mget balance debt 1) "100" 2) "0" 127.0.0.1:6379>