Redis Services (transaction) _redis

Source: Internet
Author: User
Tags cas rollback redis server
Redis Services (transaction)

This document is translated from: Http://redis.io/topics/transactions.

MULTI, EXEC, discard and WATCH are the basis of the Redis transaction.

A transaction can execute more than one command at a time with the following two important guarantees:

A transaction is a separate quarantine operation: All commands in a transaction are serialized and executed sequentially. A transaction is not interrupted by a command request sent by another client during execution.

A transaction is an atomic operation: the commands in a transaction are either all executed, or none are executed.

The EXEC command triggers and executes all the commands in a transaction: If a client has opened a transaction using MULTI, and the exec is not executed successfully because of a disconnection, then all the commands in the transaction will not be executed. On the other hand, if the client succeeds exec after the transaction is opened, all the commands in the transaction are executed.

When persisted using the AoF method, Redis writes the transaction to disk using a single write (2) command.

However, if the Redis server is killed by the administrator for some reason, or if a hardware failure occurs, only some of the transaction commands may be successfully written to disk.

If Redis finds that the AoF file is out of the question when it restarts, it quits and reports an error.

Use the REDIS-CHECK-AOF program to fix this problem: it removes information from incomplete transactions in the AoF file and ensures that the server can start successfully.

Starting with version 2.2, Redis can also implement CAS (Check-and-set) via optimistic locking (optimistic lock), referring to the second half of the documentation. Usage

The MULTI command is used to open a transaction, and it always returns OK.

After MULTI executes, the client can continue to send any number of commands to the server that are not immediately executed, but are placed in a queue, and the commands in all queues are executed when the EXEC command is invoked.

On the other hand, by invoking discard, the client can empty the transaction queue and discard the execution transaction.

Here is a transaction example that adds the values of Foo and bar two keys atomically:

> MULTI
OK

> INCR foo
QUEUED

> INCR bar
QUEUED

> EXEC
1) (integer) 1
2) ( Integer) 1

The reply to the EXEC command is an array in which each element in the array is a reply that is generated by executing the commands in the transaction. The sequence of the reply elements and the order in which the commands are sent are consistent.

When the client is in a transactional state, all incoming commands return a status reply that contains the QUEUED, and the queued commands are executed when the EXEC command is invoked. Errors in a transaction

You may encounter the following two errors when you use a transaction: A transaction may have an error in the queue before executing EXEC. For example, a command may produce syntax errors (argument number error, parameter name error, etc.), or other more serious errors, such as low memory (if the server uses MaxMemory to set the maximum memory limit). The command may fail after the EXEC call. For example, a command in a transaction might handle the wrong type of key, such as using a list command on a string key, and so forth.

For errors that occurred before EXEC execution, the client's previous practice was to check the return value of the command queue: If the command returns to QUEUED when the team is on the team, the team succeeds, or the team fails. If a command fails on the team, most clients will stop and cancel the transaction.

However, starting with Redis 2.6.5, the server records the failure of the command queue and rejects execution and automatically discards the transaction when the client invokes the EXEC command.

Before Redis 2.6.5, Redis only executed those commands that were successfully queued in the transaction, ignoring those that failed to join the queue. The new approach makes it easy to include transactions in the Pipelining (pipeline), because the replies to both send and read transactions require only one communication with the server.

There is no special treatment for the errors that occur after the EXEC command executes: Even if one or more of the commands in the transaction produces an error, the other commands in the transaction continue to execute.

It will be easier to understand the issue from the point of view of the agreement. In the following example, the execution of the Lpop command will make an error, although the syntax to invoke it is correct:

Trying 127.0.0.1
... Connected to localhost.
Escape character is ' ^] '.

MULTI
+ok

SET a 3
ABC

+queued
lpop a

+queued
EXEC

*2
+ok
-err Operation Against a key holding the wrong kind of value

EXEC returns two batch reply (bulk Reply): The first is OK, and the second one is-err. It is up to the client to decide how to use the appropriate method to represent the errors in the transaction.

The most important thing to remember is that even if a certain/certain command fails in a transaction, the other commands in the transaction queue continue to execute--redis will not stop executing the commands in the transaction.

The following example shows another case where an error occurs when the command is on the team, and the error is immediately returned to the client:

MULTI
+ok

INCR a b c
-err wrong number of arguments for ' INCR ' command

The INCR command failed because the argument to invoke the INCR command is not in the correct format. Why Redis do not support rollback (roll back)

If you have experience using relational databases, then "Redis does not roll back when a transaction fails, but continues to execute the remaining commands." This may seem a bit odd to you.

The advantages of this approach are as follows: The Redis command will only fail because of the wrong syntax (and these problems cannot be found on the team), or the command is used on the wrong type of key: This means that, from a practical standpoint, the failed command is caused by a programming error, These errors should be found in the development process and should not appear in the production environment. Because there is no need to support the rollback, the interior of the Redis can be kept simple and fast.

There is a point of view that Redis processing of transactions can produce bugs, but it should be noted that, in general, rollback does not solve the problem caused by programming errors. For example, if you had wanted to add a value of 1 to the INCR command, accidentally added 2, or performed a INCR on the wrong type of key, there was no way to handle the situation with the rollback.

Since there is no mechanism to avoid errors made by programmers themselves, and such errors usually do not occur in a production environment, Redis has opted for a simpler, faster, no rollback approach to transactions. Discard a transaction

When the discard command is executed, the transaction is discarded, the transaction queue is emptied, and the client exits from the transaction state:

redis> SET foo 1
ok

redis> MULTI
ok

redis> INCR foo
QUEUED

redis>
OK

redis> get foo
"1"
Using the Check-and-set operation to implement optimistic locks

The WATCH command can provide Check-and-set (CAS) behavior for redis transactions.

The keys being WATCH will be monitored and you will notice if the keys have been altered. If at least one of the monitored Keys is modified before exec executes, the entire transaction is canceled, and EXEC returns an empty number of bulk replies (null Multi-bulk reply) to indicate that the transaction has failed.

For example, suppose that we need to add 1 operations to a value atomically (assuming INCR does not exist).

The first thing we might do is:

val = Get MyKey
val = val + 1
SET MyKey $val

The above implementation can be done well when there is only one client. However, when multiple clients simultaneously perform such operations on the same key, a competition condition is created.

For example, if both client A and B read the original value of the key, such as 10, then two clients set the value of the key to 11, but the correct result should be 12.

With WATCH, we can easily solve such problems:

WATCH MyKey

val = Get MyKey
val = val + 1

MULTI
SET mykey $val
EXEC

Using the above code, if the MyKey value is modified by another client before EXEC executes after WATCH execution, the current client's transaction fails. What the program needs to do is to keep retrying the operation until there is no collision.

This form of locking is called an optimistic lock, and it is a very powerful locking mechanism. And because in most cases, different clients have access to different keys, collisions are generally rare, so there is usually no need to try again. About WATCH

WATCH makes the EXEC command conditional: The transaction is executed only if all the monitored keys are not modified, and the transaction is not executed if the premise is not satisfied.

If you use WATCH to monitor a key with an expiration date, even if the key expires and the transaction still works, see this post for details on this: http://code.google.com/p/redis/issues/detail?id=270

The WATCH command can be invoked multiple times. The monitoring of keys takes effect from WATCH execution until EXEC is invoked.

Users can also monitor any number of keys in a single WATCH command, like this:

redis> WATCH key1 key2 Key3
OK

When EXEC is invoked, monitoring of all keys is canceled, regardless of whether the transaction was executed successfully.

Additionally, when the client disconnects, the client's monitoring of the key is canceled.

The unwatch command with no parameters allows you to manually cancel monitoring of all keys. For some transactions that need to change multiple keys, sometimes the program needs to lock multiple keys at the same time, and then check that the current values of the keys meet the requirements of the program. When the value is not up to the requirements, you can use the Unwatch command to cancel the current monitoring of the key, abandon the transaction halfway, and wait for the next attempt at the transaction. Using WATCH to implement Zpop

WATCH can be used to create redis without a built-in atomic operation.

For example, the following code implements the original Zpop command, which can atomically eject the smallest element of the ordered set (score):

WATCH zset
element = Zrange zset 0 0
MULTI zrem zset
    element
EXEC

The program simply repeats the code until the EXEC's return value is not an empty multiple reply (null Multi-bulk reply). Redis Scripts and transactions

By definition, the script in Redis itself is a transaction, so anything that can be done in a transaction can be done in a script. And in general, scripting is easier and faster.

Since the scripting feature was introduced in Redis 2.6, the transaction function existed earlier, so Redis had two ways to handle transactions at the same time.

However, we do not intend to remove transaction functionality in a short period of time because transactions provide a way to avoid competitive conditions even without scripting, and the implementation of the transaction itself is not complex.

In the near future, however, it is possible that all users will only use scripts to implement transactions. If this happens, then we will discard and eventually remove the transaction functionality.


From:http://redisdoc.com/topic/transaction.html

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.