“This is the fifth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
The transaction
- In our daily work, we encounter many scenarios that require interventionThe transactionTo solve the
- Such as daily transfer, purchase of goods, refund and so on a series of operations
- Let’s take a look at
redis
The transaction - We are stored
A == 1, let's
A ‘increments twice and finally executes the transaction
- The specific process
-
First, when we do not execute exec, our above operations are in a transaction queue cached by Redis,
-
QUEUED is QUEUED every time we run a command
-
The transaction is executed when an exec is executed
-
Simulate the process of a transaction failure
- First of all, we
MULTI
Representation is a transaction- will
a
I’m going to put 1, and then I’m going to puta
I’m going to increase by one, and then I’m going tob
Set to stringtest
- will
b
Increment, this is an error, because strings cannot increment - Now and then
a
Increment by one and execute lastexec
Is an error
When all commands enter the queue, if there is an error, it will not be rolled back. When get a, the value of A will still be increased to 3
- will
Optimistic locking – watch
- When our business is complex with changes to data, we can only make changes in logical business
- so
redis
provideswatch
, can be inMULTI
Before usingwatch
Keep an eye on the variables, - If the
watch
An error is reported if the variable is modified after the transaction is executednil
) - As shown in the figure below
- so
- In our real business, transactions are generally maintained in code
- Such as using SpringBoot annotations to implement transactions, if maintained in Redis is not safe
- Because we can clearly integrate transactions with business scenarios in the code, we try to leave the business of atomic classes to the framework and logical code
Summary Redis supports transactions, but there is no rollback function in transactions. Each command is put into a queue 🦄