Understanding atomicity
We know that increment operations like I ++ or ++ I in Java are not atomic because increment is an instruction at our code level, but underneath the JVM, it is divided into these two steps:
- The value of I is read from the local variable table and pushed onto the operand stack
- Add 1 to the value of I in the local variable scale
If the JVM performs step 1 and another thread changes the value of I before this thread, then the value of step 2 will not be the desired value.
In Redis, there is a similar increment operation, such as the incr instruction in the string data type, which increments an integer value by one. Unlike Java increment, however, the INCR instruction is an atomic operation, because incR calls the underlying instruction of the operating system and cannot be interrupted by other threads. So incR instruction has atomicity.
Why is it called atomic?
Atomicity is basically having properties like atoms, we know that atoms have protons and neutrons in them, they form atoms, they are indivisible, and if they are divided, they are not one atom, isn’t that easy to understand? While sorting out redis, I also sorted out the latest interview questions in the last two months.Need friends can be added at the end of the article I receive, remarks: nuggets.
What is a transaction
A transaction is a series of operations that either succeed or fail at the same time. It is an atomic operation. Atoms are a whole and indivisible, and so are these operations in a transaction. Consider a scenario where A transfer of 100 yuan from Sam to Li si takes at least two steps
- Cut 100 yuan from Zhang SAN’s bank card
- Add 100 yuan to Li Si’s bank card
In the absence of a transaction, operation success could lead to the no. 1, 2, operation failure, the result is that zhang SAN have less money 100 yuan, li si money didn’t increase, zhang SAN’s 100 piece of disappear, this would be a problem, so these two operations must be placed in the transaction, or transfer success, failure or transfer, That’s what transactions do.
Redis transactions
Redis is a single-threaded program that guarantees atomicity for each instruction, but not for multiple instructions. When multiple clients are connected to the same Redis, the clients compete for CPU resources to execute rDIS instructions. Therefore, if a client wants to execute a series of instructions, it may be interrupted by other clients.
To make multiple instructions atomic, you can use redis transactions to guarantee two things:
- When executing a transaction, all commands are executed sequentially without interruption by other clients
- When executing a transaction, all commands either succeed or fail at the same time
If AOF mode is enabled, redis writes the transaction to disk before executing the command. If the Redis process suddenly hangs in the middle of a transaction, only some instructions in the transaction are successfully executed and some instructions are not yet executed. In this case, the next time Redis starts, an error is detected and Redis exits. You can use the redis-check-aof tool to repair the AOF file, delete the unsuccessful transactions in the disk, and then restart and load the AOF file. The redis is restored to the state that the transaction has not been created, and can be started normally
Transaction-related commands
Redis transaction directives are:
- multi
- exec
- discard
Let’s start with each of these commands
multi
Use the multi directive to start a transaction
127.0.0.1:6379> Set Zhangsan 1000 OK 127.0.0.1:6379> set Lisi 1000 OK 127.0.0.1:6379> multi OK 127.0.0.1:6379> incrby Zhangsan-100 QUEUED 127.0.0.1:6379> incrby lisi 100 QUEUED 1234567891011121314Copy the code
The multi command returns OK, indicating that the transaction started successfully. After the transaction is started, each subsequent correct instruction is returned to QUEUE, indicating that the command was placed in the wait QUEUE but not executed.
exec
Use the exec command to perform transactions
127.0.0.1:6379> Set Zhangsan 1000 OK 127.0.0.1:6379> set Lisi 1000 OK 127.0.0.1:6379> multi OK 127.0.0.1:6379> incrby Zhangsan-100 QUEUED 127.0.0.1:6379> incrby lisi 100 QUEUED 127.0.0.1:6379> exec # exec 1) (integer) 900 2) (integer) 1100, 123456789101112131415161718,Copy the code
After executing a transaction with exec, the results of each day’s instructions in the transaction are returned in order.
Also sorted out the Java core knowledge points, we can also have a look.Need friends can be added at the end of the article I receive, remarks: nuggets.
discard
If the transaction was successfully created but you do not want to execute it, use the discard command to cancel it
127.0.0.1:6379> multi # Enable transaction OK 127.0.0.1:6379> incrby Zhangsan-100 QUEUED 127.0.0.1:6379> incrby lisi 100 QUEUED 127.0.0.1:6379> discard # cancel transaction OK 1234567891011Copy the code
Redis transaction optimistic lock
Optimistic locking, that is, it thinks all the time there will be no problems, it will not lock, it will determine whether the data has been changed when it changes, and if it has not been changed by other people, it will update the data.
There is also an optimistic lock operation in Redis to prevent data problems, now there is the following scenario:
If you want to change the key/value in redis by transaction, another client will change the key/value before executing exec, which may cause problems after executing exec. In redis, there is a check and set (CAS) optimistic lock operation. The related command is as follows
- watch
- unwatch
watch
This key/value is monitored through the watch command, and if the key/value is found to be modified, the transaction will not be executed when the exec is called
127.0.0.1:6379> Watch Zhangsan lisi # Monitor Zhangsan and Lisi OK 127.0.0.1:6379> multi OK 127.0.0.1:6379> Incrby Zhangsan 100-100 QUEUED 127.0.0.1:6379 > incrby lisi QUEUED = = = = = = = = = = = = = = = = this time zhangsan value is modified by other client = = = = = = = = = = = = = = = = = = = = = = = 127.0.0.1:6379> exec # transaction execution failure (nil) 12345678910111213141516Copy the code
unwatch
Cancel monitoring, as opposed to the watch command. After exec execution, the watch command will unwatched after the client exits, regardless of whether the execution is successful or not
127.0.0.1:6379> Watch Zhangsan lisi # Monitor Zhangsan and Lisi OK 127.0.0.1:6379> multi OK 127.0.0.1:6379> Incrby Zhangsan -100 QUEUED 127.0.0.1:6379> incrby lisi 100 QUEUED 127.0.0.1:6379> unwatch # Cancel monitoring OK 1234567891011121314Copy the code
Errors related to transactions
Two kinds of errors can occur in redis transactions
1. Compile errors
Error caused by entering incorrect redis command after multi and before exec call
127.0.0.1:6379> multi OK 127.0.0.1:6379> sets Zhangsan 22 # Error ERR unknown command 'sets', with args beginning with: `zhangsan`, `22`, 127.0.0.1:6379> set zhangsan 22 QUEUED 127.0.0.1:6379> exec # EXECABORT Transaction discarded because of previous errors. 1234567891011Copy the code
In this case the transaction will not execute successfully
2. Runtime errors
An error caused by unsuccessful execution of the redis command after an exec call
127.0.0.1:6379> set test ABC OK 127.0.0.1:6379> multi OK 127.0.0.1:6379> incr test QUEUED 127.0.0.1:6379> set info AAA QUEUED 127.0.0.1:6379> exec 1) (error) ERR value is not an integer or out of range 2) OK 123456789101112131415Copy the code
From the execution result, it can be seen that in exec, even if there is a command error, the following commands will not be affected, but will still be executed
Finally provide free Java architecture learning materials, learning technology content includes: Spring, Dubbo, MyBatis, RPC, source code analysis, high concurrency, high performance, distributed, performance optimization, micro services advanced architecture development and so on.
Need friends can add I get, remarks: nuggets.
There are Java core knowledge points + a full set of architect learning materials and video + first-line factory interview gem + resume template can be received + Ali Meituannetease Tencent Xiaomi IQiyi Quick hand bilibilibilii interview questions +Spring source code collection +Java architecture practice ebook.