Redis supports simple transactions
Comparison of Redis and MySQL transactions
|
mysql |
redis |
turn on |
starttransaction |
muitl |
statement |
General sql |
General Command |
failed |
rollback rollback |
discard cancel |
Success |
Commit |
Exec |
Note : The difference between rollback and discard
- If you have successfully executed 2 statements , the 3 statement has an error .
- After the rollback, the first 2 statements affect the disappearance .
- Discard only ends this transaction , the impact of the first 2 statements is still
Note :
In the statement that follows Mutil , there may be 2 cases of error in the statement
- There's a problem with grammar .
This , exec , error , all statements are not executed
2. The syntax itself is correct, but there are problems with the object . For example, Zadd manipulating the list object
< Span lang= "en-us" >exec after
(If zadd operations list How to avoid it ? This , the programmer is responsible for ) requires the programmer to manually control the operation
Thinking :
I was buying a ticket.
Ticket-1, money-100
1 Zhang If I multi after exec before tickets bought by others ---namely ticket into 0
How to observe this situation and no longer submit
A pessimistic idea :
The World is full of danger, it must be someone and I Rob , to ticket lock , only I can operate . [Pessimistic lock ]
An optimistic idea :
Not so people and I Rob , therefore , I just need to note that
--No one can change the value of the ticket. [optimistic lock ]
In the Redis transaction , the optimistic lock is enabled and only the monitoring key is not altered .
Specific command ----Watch command
Example :
Redis127.0.0.1:6379>Watch Ticketokredis127.0.0.1:6379>Multiokredis127.0.0.1:6379>DECR Ticketqueuedredis127.0.0.1:6379> Decrby Money -Queuedredis127.0.0.1:6379>exec (nil)//returns nil, indicating that the ticket of the watch has changed and the transaction is canceled.Redis127.0.0.1:6379>GetTicket"0"Redis127.0.0.1:6379>Get Money" $"
Watchkey1 Key2 ... KeyN
Role : Monitor key1key2. Keyn There are no changes, if there is a change , then the transaction is canceled
Unwatch
function : Cancels all watch monitoring
Transactions in Redis