current position:Home>Redis transaction

Redis transaction

2022-05-15 07:51:15User 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

Random recommended