Advanced Redis database practical features: Transaction Control

Source: Internet
Author: User

Redis's support for transactions is still relatively simple. Redis can only ensure that the commands in the transaction initiated by one client can be executed continuously without inserting commands from other clients. Redis processes all client requests in a single thread, so it is easy to do so. Generally, redis immediately processes and returns the processing result after receiving a command from a client. However, when a client sends a multi command in a connection, the connection enters a transaction context. Subsequent commands of the connection are not executed immediately, but are put into a queue first. After the exec command is received from this connection, redis will execute all the commands in the queue in sequence. Package the running results of all commands and return them to the client. Then the connection ends the transaction context.

1. simple transaction control

The following is an example:

 
 
  1. redis 127.0.0.1:6379> get age 
  2. "33" 
  3. redis 127.0.0.1:6379> multi 
  4. OK 
  5. redis 127.0.0.1:6379> set age 10 
  6. QUEUED 
  7. redis 127.0.0.1:6379> set age 20 
  8. QUEUED 
  9. redis 127.0.0.1:6379> exec 
  10. 1) OK 
  11. 2) OK 
  12. redis 127.0.0.1:6379> get age 
  13. "20" 
  14. redis 127.0.0.1:6379> 

In this example, we can see that the two set age commands are not executed but are put into the queue. After exec is called, the two commands are executed consecutively. the result after the two commands are executed is returned.

2. How to cancel a transaction

We can call the discard command to cancel a transaction and roll back the transaction. The example above is as follows:

 
 
  1. redis 127.0.0.1:6379> get age 
  2. "20" 
  3. redis 127.0.0.1:6379> multi 
  4. OK 
  5. redis 127.0.0.1:6379> set age 30 
  6. QUEUED 
  7. redis 127.0.0.1:6379> set age 40 
  8. QUEUED 
  9. redis 127.0.0.1:6379> discard 
  10. OK 
  11. redis 127.0.0.1:6379> get age 
  12. "20" 
  13. redis 127.0.0.1:6379> 

We can see that the two set age commands were not executed this time. The discard command is used to clear the command queue of the transaction and exit the transaction context, which is also known as transaction rollback.

3. Optimistic lock complex transaction control

Before starting this section, it is necessary to briefly introduce the concept of optimistic locks to readers and give examples to illustrate how optimistic locks work.

Optimistic lock: most of them are implemented based on the record mechanism of the Data version. What is the data version? That is, add a version ID for the data. In the database table-based version solution, you can read the data by adding a "version" field to the database table, read the version number together, and Add 1 to the version number when updating later.

In this case, the version number of the submitted data is compared with the current version number of the corresponding record of the database table. If the submitted data version number is greater than the current version number of the database table, the data is updated. Otherwise, the data is considered to have expired.

Optimistic lock instance: Assume that there is a version field in the account information table in the database, the current value is 1, and the current account balance field (balance) is $100. The following describes how optimistic locks are implemented using time series tables:

Operator Operator B
(1) operator A reads user information at this time. version = 1) and prepares to deduct $50 $100-$50 from the account balance) (2) During operator A's operation, operator B also reads this user information. At this time, version = 1 ), and you want to deduct $20 $100-$20 from your account balance)
(3) operator A completes the modification and adds the data version number to 1. At this time, version = 2), along with the balance after account deduction = $50), submits the data to the database for updates, at this time, because the submitted data version is later than the current version of the database record, the data is updated, and the database record version is updated to 2
(4) Operator B completed the operation and added the version number to 1 version = 2) and tried to submit data balance = $80 to the database. However, it was found that, the version number of the data submitted by operator B is 2, and the database record current version is 2, which does not meet the optimistic lock policy that "the submitted version must be later than the current version to be updated". Therefore, submission of operator B is rejected

This avoids the possibility that operator B will overwrite operator A's operation results by modifying the old data based on version = 1.

Now optimistic locks are much better than pessimistic locks. Does redis also support them? The answer is yes. redis supports optimistic locks from 2.1.0. You can explicitly use watch to lock a key to avoid a series of problems caused by pessimistic locks.

Redis optimistic lock instance:

Suppose there is an age key. We open two sessions to assign values to the age. Let's take a look at the results.

Session 1 Session 2
(1) Step 4: redis 127.0.0.1: 1st> get age "10" redis 127.0.0.1: 6379> watch age OK redis 127.0.0.1: 6379> multi OK redis 127.0.0.1: 6379>
(2) Step 4: redis 127.0.0.1: 2nd> set age 30 OK redis 127.0.0.1: 6379> get age "30" redis 127.0.0.1: 6379>
(3) Step 4: redis 127.0.0.1: 3rd> set age 20 QUEUED redis 127.0.0.1: 6379> exec (nil) redis 127.0.0.1: 6379> get age "30" redis 127.0.0.1: 6379>

You can see in

Step 1: Session 1 has not had time to modify the age value.

Step 2: Session 2 has set the age value to 30.

Step 3: Session 1 wants to set the age value to 20, but the result 1 is returned as nil, which indicates that the execution fails. Then, let's take the value of age as 30, this is caused by the optimistic lock on age in Session 1.

The watch command monitors the given key. When exec, if the monitored key changes from the watch call, the entire transaction will fail. You can also call watch to monitor multiple keys multiple times. In this case, you can apply an optimistic lock to the specified key. Note that the key of watch is valid for the entire connection, and the transaction is the same. If the connection is disconnected, monitoring and transactions are cleared automatically. Of course, the exec, discard, and unwatch commands will clear all monitoring in the connection.

Redis transaction implementation is so simple, of course there will be some problems. The first problem is that redis can only ensure the continuous execution of each command of the transaction. However, if a command in the transaction fails, other commands are not rolled back. For example, the command type used does not match. The following example illustrates the problem:

 
 
  1. redis 127.0.0.1:6379> get age 
  2. "30" 
  3. redis 127.0.0.1:6379> get name 
  4. "HongWan" 
  5. redis 127.0.0.1:6379> multi 
  6. OK 
  7. redis 127.0.0.1:6379> incr age 
  8. QUEUED 
  9. redis 127.0.0.1:6379> incr name 
  10. QUEUED 
  11. redis 127.0.0.1:6379> exec 
  12. 1) (integer) 31 
  13. 2) (error) ERR value is not an integer or out of range 
  14. redis 127.0.0.1:6379> get age 
  15. "31" 
  16. redis 127.0.0.1:6379> get name 
  17. "HongWan" 
  18. redis 127.0.0.1:6379> 

In this example, we can see that age is a number, so it can have auto-increment operations, but name is a string and cannot be auto-incrementing. Therefore, an error is reported, the entire transaction will be rolled back based on the traditional relational database concept, but we can see that redis has committed executable commands, therefore, this phenomenon is awkward for friends who are used to relational database operations. This is what redis needs to improve today.

Edit recommendations]

  1. Redis2.6 release a new function Overview
  2. Five precautions for using Redis
  3. High Availability of Redis-Failover transition Solution
  4. What can Redis do? 11 Web application scenarios
  5. Comprehensive Evaluation of mainstream NoSQL databases in Redis

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.