Transaction and distributed lock
Transaction: a set of commands
The main commands multi and exec
multi set a 1 sadd s1 a ...... exec
Error handling
- (1) Syntax error
127.0.0.1:6379> multi OK 127.0.0.1:6379> set a 1 QUEUED 127.0.0.1:6379> set b (error) ERR wrong number of arguments for 'set' command 127.0.0.1:6379> silk c (error) ERR unknown command 'seta' 127.0.0.1:6379> exec (error) EXECABORT Transaction discarded because of previous errors. 127.0.0.1:6379> get a (nil) 127.0.0.1:6379>
As long as there is any grammatical error, the correct one will not be executed
- (2) Operation error For
example, a is a string type, and then follow the hash operation hset a k1 v1
127.0.0.1:6379> keys * (empty list or set) 127.0.0.1:6379> set a 1 OK 127.0.0.1:6379> type a string 127.0.0.1:6379> multi OK 127.0.0.1:6379> set n 1 QUEUED 127.0.0.1:6379> hset a k1 v1 QUEUED 127.0.0.1:6379> set m 2 QUEUED 127.0.0.1:6379> exec 1) OK 2) (error) WRONGTYPE Operation against a key holding the wrong kind of value 3) OK 127.0.0.1:6379> mget n m 1) "1" 2) "2" 127.0.0.1:6379> type a string
The correct instruction is executed, redis transaction does not support rollback, so the developer needs to deal
with the standardized key name in development by himself , and this problem generally does not occur
DISCARD cancel transaction
Distributed lock
setnx a:lock 1 expire a:lock 5 del a:lock
In order to enable setnx and expire to be executed together, and the execution of expire depends on the success of setnx, obviously it is not true to put in the transaction
Atomic instructions combined with setnx and expire
set a:lock 1 ex 10 nx
The above is this atomic operation with a:lock of 1 and a validity of 10s
Timeout problem
Redis distributed locks cannot solve the timeout problem. If the logic between locking and releasing the lock is executed too long to exceed the lock timeout limit, problems will occur. Because the lock held by the first thread expires at this time and the logic of the critical section has not been executed yet, the second thread re-holds the lock in advance at this time, resulting in the critical section code not being strictly executed serially. .
To avoid this problem, Redis distributed locks should not be used for long-term tasks. If it does happen occasionally, the wavelet disorder in the data may need manual intervention to solve