Detailed explanation of redis transaction management

transaction management

Redis provides transaction management functions, which can be achieved through Redis's MULTI, EXEC, WATCH and DISCARD commands.

  1. Start a transaction:
    Use the MULTI command to start a transaction, which means that all commands executed next belong to this transaction.

    Example:

    MULTI
    
  2. Execute transaction operations:
    Multiple commands can be executed in a transaction. These commands will not be executed immediately, but will be placed in a queue.

    Example:

    SET key1 value1
    GET key1
    INCR key2
    
  3. Submit transaction:
    Use the EXEC command to submit the transaction, and Redis will execute all commands in the queue in the order of the commands.

    Example:

    EXEC
    

    After executing the EXEC command, Redis will execute the corresponding transaction command and return the execution results of each command.

  4. Watch for key changes:
    You can use the WATCH command to watch for changes in one or more keys. If a monitored key is modified during transaction execution, the transaction will be aborted.

    Example:

    WATCH key1 key2
    
  5. Cancel transaction:
    If you need to cancel the current transaction before executing the transaction, you can use the DISCARD command.

    Example:

    DISCARD
    

Transaction characteristics:

  • A Redis transaction is a single isolated sequence of operations. From start to commit, Redis will not interrupt the sequence or handle requests from other clients.
  • Before the EXEC command, the commands in the transaction are only entered into the queue and are not actually executed, so even if an error occurs in one of the commands, it will not affect the execution of other commands.
  • Redis does not provide a rollback mechanism. Once a transaction is committed, all commands in it will be executed and cannot be undone.
  • If the key monitored by WATCH is modified before the EXEC command is executed, the transaction will be aborted.

It should be noted that Redis transactions do not have the ACID characteristics like relational databases. It is mainly used to package multiple commands together to ensure the atomic execution of these commands, but there is no isolation and durability features between transactions.

Optimistic locking and pessimistic locking

Optimistic locking and pessimistic locking in Redis are two different strategies used to ensure data consistency when dealing with concurrent access.

  1. Optimistic locking:

    • Implementation method: Optimistic locking is implemented based on data version number or timestamp. Before reading the data, the version number or timestamp of the data will be obtained, and then compared with the version number or timestamp when updating the data. If they match, the update is successful. Otherwise, it means that other clients have modified the data.
    • Actual operation: In Redis, 使用WATCH命令监视指定的键use MULTI/EXEC to combine multiple commands to operate. If the keys monitored during execution are modified by other clients, the transaction will abort execution.
    • Application scenario: Suitable for scenarios with many read operations and few write conflicts.
  2. Pessimistic lock:

    • Implementation method: Pessimistic locking is implemented based on the locking mechanism, that is, locking is directly performed before accessing the data to ensure that other transactions cannot access the same data before the current transaction is completed.
    • Actual operation: In Redis, you can use the 设置带有NXlock key of the SET command (create if it does not exist) parameter. If the setting is successful, it means that the lock is obtained, and the lock is released after the operation is completed.
    • Application scenario: Suitable for scenarios with many write operations and write conflicts.

The appropriate lock strategy needs to be selected based on the specific situation. Optimistic locks will not block and wait when encountering concurrency conflicts, but solve concurrency problems through detection; pessimistic locks will lock directly, which may cause other transactions to wait, but can ensure data consistency.

watch command implements optimistic locking

The WATCH command in Redis is used to implement optimistic locking. It can monitor one or more keys and check whether these keys have been modified during the execution of a transaction, and abort the execution of the transaction if so.

The steps to use the WATCH command are as follows:

  1. Use the MULTI command to start a transaction.
  2. Use the WATCH command to monitor the keys that need to be checked.
  3. Perform a series of read operations to obtain the data that needs to be modified.
  4. If 其他客户端修改了被监视的键, the transaction will 中止be executed.
  5. If the key has not been modified, continue executing other commands in the transaction.
  6. Use the EXEC command to commit the transaction.

The sample code is as follows:

WATCH key1 key2 ...
MULTI
// 在事务中执行读取、修改等操作
EXEC

When executing the EXEC command, Redis will check whether the key monitored by the WATCH command has been modified by other clients. If it has been modified, the transaction will abort execution and return an empty result. Otherwise, the transaction will execute its commands in order.

The WATCH command can embed optimistic locking logic in the client code to ensure that data modifications in a concurrent environment are synchronized and consistent.

watch command example

Example: When using Redis's WATCH command for optimistic lock processing, two transactions can be used to illustrate how it works.

Suppose there are two clients 同时operating on the same key, one client executes transaction A and the other client executes transaction B.

Code example for transaction A:

WATCH key
MULTI
SET key "New Value"
EXEC

Code example for transaction B:

WATCH key
MULTI
SET key "Another Value"
EXEC

两个事务的执行都失败

Below is an explanation of the execution process:

  1. Initial state: Assume that the value of "key" is "Initial Value".
  2. Transaction A starts executing:
    • Use the WATCH command to monitor "key".
    • Execute the command in transaction A.
    • Try setting the value of "key" to "New Value".
    • If no other client modified "key" during execution, transaction A is committed and the value of "key" is updated to "New Value".
    • If other clients modify "key" during execution, transaction A is aborted and the value of "key" will not be modified.
  3. Transaction B starts executing:
    • Use the WATCH command to monitor "key".
    • Execute the command in transaction B.
    • Try setting the value of "key" to "Another Value".
    • If no other client modified "key" during execution, transaction B is committed and the value of "key" is updated to "Another Value".
    • If other clients modify "key" during execution, transaction B is aborted and the value of "key" will not be modified.

By using the WATCH command, both transaction A and transaction B will monitor changes in "key" during execution. If other clients modify "key", the current transaction will be aborted to ensure data consistency and the correctness of concurrent operations.

Guess you like

Origin blog.csdn.net/drhnb/article/details/132197117