6.Redis事务
- 是什么:
- Redis事务VS数据库事务
- 怎么玩
- Errors inside a transaction
- Watch监控:
- Optimistic locking using check-and-set
是什么:
Redis Transactions allow the execution of a group of commands in a single step, they are centered around the commands MULTI, EXEC, DISCARD and WATCH. |
Redis事务VS数据库事务
怎么玩
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379(TX)> set k1 v1
QUEUED
127.0.0.1:6379(TX)> lpush list 1 2 3
QUEUED
127.0.0.1:6379(TX)> set k2 v2
QUEUED
127.0.0.1:6379(TX)> incr count
QUEUED
127.0.0.1:6379(TX)> exec
1) OK
2) (integer) 3
3) OK
4) (integer) 1
127.0.0.1:6379> set k3 v3
OK
127.0.0.1:6379> DISCARD
(error) ERR DISCARD without MULTI
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379(TX)> set k1 v1
QUEUED
127.0.0.1:6379(TX)> set k2 v2
QUEUED
127.0.0.1:6379(TX)> set k3 v3
QUEUED
127.0.0.1:6379(TX)> DISCARD
OK
127.0.0.1:6379> key *
(error) ERR unknown command 'key', with args beginning with: '*'
127.0.0.1:6379> set key list
OK
127.0.0.1:6379> set key count
OK
127.0.0.1:6379> key *
(error) ERR unknown command 'key', with args beginning with: '*'
127.0.0.1:6379> key *
(error) ERR unknown command 'key', with args beginning with: '*'
127.0.0.1:6379> key --help
(error) ERR unknown command 'key', with args beginning with: '--help'
127.0.0.1:6379> key @help
(error) ERR unknown command 'key', with args beginning with: '@help'
127.0.0.1:6379> key -help
(error) ERR unknown command 'key', with args beginning with: '-help'
127.0.0.1:6379> keys *
1) "k3"
2) "count"
3) "key"
4) "k1"
5) "mylist"
6) "list"
7) "k2"
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379(TX)> set k1 1111
QUEUED
127.0.0.1:6379(TX)> keys *
QUEUED
127.0.0.1:6379(TX)> set k2 2222
QUEUED
127.0.0.1:6379(TX)> INCR count
QUEUED
127.0.0.1:6379(TX)> set k3
(error) ERR wrong number of arguments for 'set' command
127.0.0.1:6379(TX)> EXEC
(error) EXECABORT Transaction discarded because of previous errors.
127.0.0.1:6379> get k1
"v1"
127.0.0.1:6379> get 2
(nil)
127.0.0.1:6379> get k2
"v2"
127.0.0.1:6379>
Errors inside a transaction
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379(TX)> set k1 abc
QUEUED
127.0.0.1:6379(TX)> get k1
QUEUED
127.0.0.1:6379(TX)> set email 123@126.com
QUEUED
127.0.0.1:6379(TX)> INCR
(error) ERR wrong number of arguments for 'incr' command
127.0.0.1:6379(TX)> INCR email
QUEUED
127.0.0.1:6379(TX)> get count
QUEUED
127.0.0.1:6379(TX)> EXEC
(error) EXECABORT Transaction discarded because of previous errors.
Watch监控:
(悲观锁(Pessimistic Lock), 顾名思义,就是很悲观,每次去拿数据的时候都认为别人会修改,所以每次在拿数据的时候都会上锁,这样别人想拿这个数据就会block直到它拿到锁。)
(乐观锁(Optimistic Lock), 顾名思义,就是很乐观,每次去拿数据的时候都认为别人不会修改,所以不会上锁,但是在更新的时候会判断一下在此期间别人有没有去更新这个数据。)
(乐观锁策略:提交版本必须大于 记录当前版本才能执行更新。)
Optimistic locking using check-and-set
127.0.0.1:6379> WATCH balance
OK
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379(TX)> set balance 150
QUEUED
127.0.0.1:6379(TX)> EXEC
#此处下面则会返回一个nil值,报告本次失效。
(nil)
127.0.0.1:6379>
and EXEC returns a Null reply to notify that the transaction failed. |