Home > Database > Redis > body text

How to ensure atomicity in redis

Release: 2019-07-08 09:16:01
Original
7022 people have browsed it

How to ensure atomicity in redis

Atomicity:

Atomicity is a characteristic of database transactions. In the context of database transactions, atomicity refers to: all operations in a transaction (transaction) are either completely completed or not completed, and will not end somewhere in the middle.

For Redis, the atomicity of a command means that an operation cannot be subdivided, and the operation is either executed or not.

The reason why Redis operations are atomic:

The reason why Redis operations are atomic is because Redis is single-threaded.

Performance of Redis in concurrency:

The API of Redis is an atomic operation, so are multiple commands also atomic in concurrency?

has the following code:

$redis= newRedis();
$redis->connect('127.0.0.1',6379);
for($i= 0;$iget('val');
$num++;
$redis->set('val',$num);
usleep(10000);
}
Copy after login

Use two terminals to execute the above program and find that the result of val is less than 2000. Then you can know that executing multiple Redis commands in the program is not Atomic, this is the same as the performance of ordinary databases.

If you want to achieve atomicity in the above program, you can change get and set into single command operations, such as incr, or use Redis transactions, or use Redis Lua to implement them.

For Redis, executing APIs such as get, set, and eval are tasks one by one. These tasks will be executed by Redis threads. The tasks are either executed successfully or failed. This is why Redis commands are atomic.

All APIs provided by Redis itself are atomic operations. Transactions in Redis actually ensure the atomicity of batch operations

For more Redis related knowledge, please visit Redis usage tutorial column!

The above is the detailed content of How to ensure atomicity in redis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template