Redis supports simple transactions
Comparison of Redis and MySQL transactions
|
Mysql |
Redis |
Open |
Start transaction |
Muitl |
Statement |
Normal SQL |
General Command |
Failed |
Rollback rollback |
Discard Cancel |
Success |
Commit |
Exec |
Note: The difference between rollback and discard
If 2 statements have been executed successfully, the 3rd 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
1: Grammar is a problem,
This, exec, error, all statements are not executed
2: The syntax itself is correct, but there is a problem with the applicable object. For example, Zadd manipulating the list object
After exec, the correct statements are executed and the inappropriate statements are skipped.
(If Zadd operations list how can this be avoided? This is the programmer's responsibility)
Thinking:
I was buying a ticket.
Ticket-1, money-100
And the ticket only 1, if after I multi, and exec before, the ticket was bought by others---namely ticket becomes 0.
How can I observe this situation and not 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
Cases:
Redis 127.0.0.1:6379> Watch Ticket
Ok
Redis 127.0.0.1:6379> Multi
Ok
Redis 127.0.0.1:6379> DECR Ticket
QUEUED
Redis 127.0.0.1:6379> Decrby Money 100
QUEUED
Redis 127.0.0.1:6379> exec
(nil)//return nil, indicating that the monitoring ticket has changed and the transaction is canceled.
Redis 127.0.0.1:6379> Get Ticket
"0"
Redis 127.0.0.1:6379> Get Money
"200"
Watch Key1 Key2 ... KeyN
Role: Monitor Key1 key2. Keyn There are no changes, if there is a change, then the transaction is canceled
Unwatch
Function: Cancels all watch monitoring
Redis Transaction and lock applications