current position:Home>Redis transaction
Redis transaction
2022-05-15 07:51:15【User 7353950】
Redis Business profile
Redis The basic functions of transactions are MULTI、EXEC、DISCARD And WATCH Etc . among ,
● MULTI The command is used to start Redis The business of , Set the client to the transaction state .
● EXEC The command is used to commit a transaction , Execution from MULTI The command queue before this command , At this point, the client becomes non transactional .
● DISCARD Command to cancel a transaction , After the execution of the command , All commands in the transaction queue will be cleared , And the client exits from the transaction state . You can think of it as transaction rollback , however Redis The database does not have a transaction rollback mechanism .
● WATCH Command is used to monitor key value pairs , It makes the EXEC The order needs to be executed conditionally , On the premise that all monitored keys have not been modified , Transactions can be executed normally . If the monitored key value pair changes , Then the transaction will not be executed .
Redis A transaction is essentially a set of commands ,Redis The server serializes this set of commands first , And then one time 、 According to the order 、 Exclusive serial ( one by one ) Execute this set of commands , And will not execute other client commands on the way of executing transactions .
Redis A transaction can only ensure that the commands in a transaction requested by a client can be executed continuously
When the server receives the command sent by the client, it is MULTI、EXEC、WATCH、DISCARD 4 When any one of the commands , The server will execute this command immediately .
contrary , When the server receives the command sent by the client, it is MULTI、EXEC、WATCH、DISCARD 4 When other than one command , The server will not execute this command immediately , Instead, put the command into a transaction queue , Then return QUEUED Identify to the client .
Every Redis Each client has its own transaction state , and mstate Property saves the transaction state of the client . The transaction status consists of a transaction queue and a counter for queued commands . among , The transaction queue is a multiCmd An array of structs of type , It uses first in first out (FIFO) The way to keep the order to join the team , The first to queue command will be placed in front of the array , Execute first ; Then the order to join the queue is put behind the array , After execution . Every... In this array multiCmd The structure holds the information of a queue command , Specifically, it includes the pointer to the command implementation function 、 The parameters of the command and the number of parameters .
ACID characteristic
Atomicity : When the client uses MULTI The command successfully opens a transaction context , perform EXEC command , If multiple commands in the middle of the queue are not executed successfully , Or all failure .
When the client is in the transaction on state , Every time you enter a command , Will return a content of QUEUED The result of the reply
In execution EXEC After the command , The execution result will be returned as an array , Each element in the array is the result of the command execution in the transaction . The output order of the result is consistent with the order in which the command enters the queue after the transaction is started .
However Redis The database does not support transaction rollback . towards Redis Insert a command into the transaction queue , If you encounter a command format error , Team entry failure , It will cause the whole transaction to fail . If the syntax format of a command in the transaction is correct , But when executing, an error is reported because the type or key does not exist , Then its whole business will continue , Instead of terminating the execution , Until all the commands of this transaction are executed .
Uniformity : Consistency of affairs means , The database is consistent before executing transactions , After executing the transaction , Whether the transaction is executed successfully or failed , The data in the database should also be consistent .
When there is an error command , Or the command format is wrong . The server will refuse to execute transactions with errors in the queue process , Caused the transaction execution to fail , So as to ensure the consistency of the database .
When the order to join the team succeeds , But an error occurred during the execution . Such as INCRBY username 8 command , Then the wrong command will be detected by the server , And make corresponding error handling , The execution of these commands will not be affected by errors , It will not modify the database , It has no impact on the consistency of transactions .
When something happens ( Such as power failure 、 Server down 、 Server crash, etc ), Cause transaction execution error . At this time, the consistency of the database is often guaranteed according to the persistence method used by the server , As follows .
* The server did not turn on persistence , When the server restarts , There will be no data in the database , At this time, the consistency of the database can be guaranteed .
* The server is on RDB or AOF Persistence , In the process of executing a transaction , failure , Will not cause database inconsistency .RDB or AOF The database data is saved in the file , According to RDB or AOF File to restore the data to the state before the transaction is executed . If it's on RDB or AOF Persistence mode , But I can't find RDB or AOF file , So after the server restarts , The database will be blank , It can also ensure the consistency of the database .
Isolation, :Redis Database is a key value pair storage database realized by single process and single thread model , When executing transaction commands and other related commands , The single thread method is adopted . In the process of executing a transaction , The server can guarantee that the transaction will not be interrupted , therefore Redis Transactions are always implemented serially , Before the last transaction is completed , Other commands will not be executed , This is it. Redis Isolation of transactions .
persistence :Redis Database is a key value pair storage database realized by single process and single thread model , When executing transaction commands and other related commands , The single thread method is adopted . In the process of executing a transaction , The server can guarantee that the transaction will not be interrupted , therefore Redis Transactions are always implemented serially , Before the last transaction is completed , Other commands will not be executed , This is it. Redis Isolation of transactions .
● If Redis The server does not use any persistence method , Then transactions are not persistent . If the server fails ( Such as shutdown 、 power failure 、 collapse ), All data on the server, including transaction data, will be lost .
● If Redis Server used AOF Persistence mode :
* When Redis The configuration file (redis.conf) Medium appendfsync The value of the property is always when , Can guarantee Redis Transactions are persistent . Every time the server executes relevant commands , Including transaction commands , The program will call and execute sync Synchronization function , Save the command data to the system hard disk in time , This ensures the persistence of transactions .
* When Redis In the configuration file appendfsync The value of the property is everysec when , The server program will run every 1 Perform data synchronization once per second , And save the data to the hard disk . If the server goes down and fails , It may happen just when the data is waiting for synchronization 1 In seconds , It will lead to data loss , Therefore, the persistence of transactions cannot be guaranteed .
* When Redis In the configuration file appendfsync The value of the property is no when , The operation that the server commands the data to be synchronously saved to the hard disk will be controlled by the operating system , therefore , Transaction data is in the process of synchronization , May be lost for some reason , This situation also does not guarantee the persistence of transactions . Later chapters will describe in detail Redis The persistence of .
● If Redis Server used RDB Persistence mode , that , Only when specific storage conditions are met , The server will execute BGSAVE command , Save data . And if it's asynchronous BGSAVE command , Then the server cannot guarantee to save the transaction data to the hard disk at the first time , Therefore, the persistence of transactions cannot be guaranteed . let me put it another way ,RDB Persistence cannot guarantee the persistence of transactions .
Pessimistic lock and optimistic lock
Pessimistic locking : Every time I go to the database to get data, I think others will modify the data , So it locks the data every time it fetches it , Don't let others use it , If someone wants to take this data, it will block until it releases the lock 、 Until someone else gets the lock . In traditional relational databases , A lot of pessimistic locks are used , Like a line lock 、 Table locks 、 Read the lock 、 Write locks, etc.
Optimism lock : Every time I go to the database to get data , All think that others will not modify these data , So it won't lock these data . But it is also very careful , Every time you update these data , Will judge whether others have updated these data during this period . If someone else has updated these data , It will abandon this update ; contrary , If someone else hasn't updated these data , It will update the data . Optimistic locking is more suitable for multi read applications , Can improve throughput .( Below WATCH Command is an optimistic lock )
The transaction WATCH command
The transaction WATCH Commands are used to monitor commands in transactions . With WATCH Command monitoring , Would make EXEC The order needs to be executed conditionally , Only when all are WATCH The database keys monitored by the command have not been modified , This transaction can be executed successfully . If any one of the monitored database keys is modified , Then this transaction will fail .
Use UNWATCH Order to cancel WATCH Command to monitor database keys
Usage method :
WATCH name age#WATCH Command to monitor at the same time name Key sum age key
MULTI# Open transaction context
...
copyright notice
author[User 7353950],Please bring the original link to reprint, thank you.
https://en.chowdera.com/2022/131/202205102047500658.html
The sidebar is recommended
- Which securities company does qiniu school recommend? Is it safe to open an account
- Hyperstyle: complete face inversion using hypernetwork
- What activities are supported by the metauniverse to access reality at this stage?
- P2P swap OTC trading on qredo
- Google | coca: the contrast caption generator is the basic image text model
- SIGIR 2022 | Huawei reloop: self correcting training recommendation system
- Whether you want "melon seed face" or "national character face", the "face changing" technology of Zhejiang University video can be done with one click!
- Sorting of naacl2022 prompt related papers
- Servlet create project
- "Chinese version" Musk was overturned by the original: "if it's true, I want to see him"
guess what you like
[network security] web security trends and core defense mechanisms
[intensive reading] object detection series (10) FPN: introducing multi-scale with feature pyramid
007. ISCSI server chap bidirectional authentication configuration
2021-03-09
plot_ Importance multi classification, sorting mismatch, image value not displayed
[intensive reading] object detection series (XI) retinanet: the pinnacle of one stage detector
How to install MFS environment for ECS
[intensive reading] the beginning of object detection series (XII) cornernet: anchor free
Open source sharing -- a record of students passing through time
MOT:A Higher Order Metric for Evaluating Multi-object Tracking
Random recommended
- How to develop a distributed memory database (1)
- Reverse engineers reverse restore app and code, and localization is like this
- One line command teaches you how to export all the libraries in anaconda
- Bi tools are relatively big. Let's see which one is most suitable for you
- Read the history of database development
- Self cultivation of coder - batterymanager design
- Technology application of swift phantom type phantom in Apple source code learning
- Swiftui advanced skills: what is the use of the technology of swift phantom type phantom
- Swiftui advanced animation Encyclopedia of complex deformation animation is based on accelerate and vector arithmetic (tutorial includes source code)
- What problems remain unsolved in swiftui in 2022
- I'll set the route for fluent
- Flutter drawing process analysis and code practice
- Emoji language commonly used icon collection (interesting Emoji)
- 5.14 comprehensive case 2.0 - automatic induction door
- How to deploy redis service on k8s top?
- Importance of data warehouse specification
- Idea automatically generates serialization ID
- Why is it recommended not to use select * in MySQL?
- Let's talk about why redis needs to store two data structures for the same data type?
- Domain lateral move RDP delivery
- gDvuGqjmDS
- [learn slam orb_slam2 or slam3 from scratch] summary of all blog articles
- 20000 + star ultra lightweight OCR system pp-ocrv3 effect increased by 5% - 11%!
- A configurable canvas clock - Super multi style
- The pp-ocrv3 effect of 20000 + star ultra lightweight OCR system is further improved by 5% - 11%
- MySQL's golden rule: "don't use select *"
- True interview question: why does redis store a data type twice?
- High threshold for large factories? Five exclusive PDFs inside Alibaba will take you forward and win the offer
- Is it really hard to find a job? How on earth can I find a job with high salary without worrying about being laid off
- How to design knowledge center? (code attached)
- OWASP top 10 vulnerability analysis
- Are you still writing comment templates manually? Idea can generate annotation templates of classes and methods with one click. Click in if you don't know
- Numpy core syntax and code sorting summary!
- Can you believe that the swoole timer can realize millisecond task scheduling?
- Detailed explanation of art template engine
- Telephone subsystem of openharmony source code analysis -- call flow
- Yixin Huachen: how to do a good job in digital transformation in the power industry?
- One stop collaboration is really delicious - apipost
- Notes on modern algebra and series of questions: Chapter 1 (introduction of algebraic system)
- Notes on modern algebra and serialization of question types: Chapter 2 (properties of binary operation)