This is the 16th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Redis, as a non-relational database, also has transaction operations.

Redis transactions can execute multiple commands at once with three important guarantees:

(1) Batch operations are placed in the queue cache before sending EXEC commands.

(2) After receiving the EXEC command, the transaction is executed. Any command in the transaction fails to be executed, and other commands are still executed.

(3) During transaction execution, command requests submitted by other clients will not be inserted into the command sequence of transaction execution.

A transaction goes through the following three phases from inception to execution:

(1) Start transaction.

(2) Command to join the ranks.

(3) Execute transactions.

However, there is a big difference between redis transaction and mysql transaction. Data will be rolled back if errors occur during mysql execution, while data will not be rolled back if errors occur during Redis transaction execution.

Redis transactions can be thought of as a script that executes commands in batches.

What matters here is not whether each command executed successfully during the transaction, but whether the current transaction was executed successfully.

One: Linux command

127.0.0.1:6379> multi OK 127.0.0.1:6379>setA aAAA QUEUED // Set the key 127.0.0.1:6379>setB BBBB QUEUED // set the health value 127.0.0.1:6379>set127.0.0.1:6379> c CCCC QUEUED //exec
1) OK
2) OK
3) OK
Copy the code

Two: PHP command

// Start the transaction$res = $redis->multi();
 
    $res = $redis->set('a'.'aaa');
    var_dump($res);
    echo "<hr>";
 
    $res = $redis->set('b'.'bbb');
    var_dump($res);
    echo "<hr>";
 
    $res = $redis->set('c'.'bbb');
    var_dump($res);
    echo "<hr>"; // Execute a transaction$res = $redis->exec(a); var_dump($res);
Copy the code

The above is just a simple application of Redis transaction, roughly so, mainly application it is a batch command.

Three: Optimistic lock implementation based on Redis transaction

Explanation: Optimistic Lock, as the name suggests, is Optimistic.

Every time I went to pick up the data, I thought no one would change it, so I wouldn’t lock it.

The watch command will monitor the given key, and the whole transaction will fail if the monitored key has changed since the call to watch during exec.

Watch can also be called to monitor multiple keys multiple times. This allows optimistic locks to be added to the specified key.

Note that the watch key is valid for the entire connection, as are transactions.

If the connection is disconnected, both monitoring and transactions are automatically cleared.

Of course, the exec, discard, and unwatch commands remove all monitoring from the connection.

// Monitor count$redis->watch("count"); // Start the transaction$redis->multi(); / / operation count$time = time();
    $redis->set("count".$time); // Simulate other processes concurrentlysetTo perform the count operation, perform the following operations // on the shell clisetcount issimulate; sleep(40); // Commit the transaction$res = $redis->exec(a);$result = $redis->get('count');
 
    if ($res) {// Success...echo "success:" . $result ;
        echo "<hr>";
        return; } // failed...echo "fail:" . $result ;
    echo "<hr>";
 
Copy the code

This test code may need to be explained:

First of all, we will monitor the key count. After starting the transaction, we will set the value of the key count to the current timestamp, and the program will sleep for 40 seconds before executing the transaction operation. This is the ideal case where the above code executes the transaction successfully without any external influence

Success: 1502547852Copy the code

After executing the transaction in the browser, the program sleeps for 40 seconds. During this time, simulate another process to modify the value of the count key and execute set Count isSIMULATE in the shell. , the value of the key monitored by watch is changed by another process during the transaction execution, then the transaction execution fails. The output

fail:issimulate
Copy the code

In retrospect, when different processes modify the same value, using transactions is like adding an optimistic lock to it.

Four: redis transaction command

The serial number

Commands and Description

1

DISCARD Cancels a transaction and abandons all commands in a transaction block.Copy the code

2

EXEC executes all commands within the transaction block.Copy the code

3

MULTI marks the start of a transaction block.Copy the code

4

UNWATCH Disables the WATCH command from monitoring all keys.Copy the code

5

WATCH key [key ...] Monitor a key (or keys) and interrupt the transaction if the key (or keys) is changed by another command before the transaction executes.Copy the code

For good suggestions, please enter your comments below.

Welcome to my blog guanchao.site

Welcome to applets: