search
HomeDatabaseRedisWhat is the maximum concurrency of redis?

Concurrency issues in redis

I have been using redis as a cache for a long time. Redis runs as a single process, and commands are executed one after another. I thought there would be no concurrency problems, but it wasn’t until I saw the relevant information today that I suddenly realized it.

What is the maximum concurrency of redis?

Specific problem example

There is a key, assuming the name is myNum, and Arabic numerals are stored in it. Assume the current value is 1. If there are multiple connections operating on myNum, there will be concurrency problems. Suppose there are two connections linkA and linkB. Both connections perform the following operations, take out the value of myNum, 1, and then save it back to see the following interaction:

linkA get myNum => 1linkB get myNum => 1linkA set muNum => 2linkB set myNum => 2

After performing the operation, the result Probably 2, which is inconsistent with the 3 we expected.

Look at a specific example:

<?phprequire "vendor/autoload.php";$client = new Predis\Client([
&#39;scheme&#39; => &#39;tcp&#39;,
&#39;host&#39; => &#39;127.0.0.1&#39;,
&#39;port&#39; => 6379,]);for ($i = 0; $i < 1000; $i++) { $num = intval($client->get("name"));
$num = $num + 1;
$client->setex("name", $num, 10080);
usleep(10000);}

Set the initial value of name to 0, and then use two terminals to execute the above program at the same time. The final value of name may not be 2000, but a < ;The value of 2000 proves the existence of our above concurrency problem. How to solve this?

Transactions in redis

There are also transactions in redis, but this transaction is not as perfect as in mysql. It only guarantees consistency and isolation and does not satisfy atomicity. sex and durability.

redis transactions use multi, execcommands

atomicity, redis will execute all commands in the transaction, even if there are executions in the middle There will be no rollback on failure. Kill signals, host downtime, etc. cause transaction execution to fail, and redis will not retry or roll back.

Persistence, the persistence of redis transactions depends on the persistence mode used by redis. Unfortunately, various persistence modes are not persistent.

Isolation, redis is a single process. After starting a transaction, all commands of the current connection will be executed until the exec command is encountered, and then commands of other connections will be processed.

Consistency, after reading the document, I think it’s quite ridiculous, but it seems to be correct.

Transactions in redis do not support atomicity, so the above problem cannot be solved.

Of course redis also has a watch command, which can solve this problem. See the following example, execute watch on a key, and then execute the transaction. Due to the existence of watch, he will Monitor key a. When a is repaired, subsequent transactions will fail to execute. This ensures that multiple connections come at the same time, all monitoring a. Only one can execute successfully, and the others will return failure.

127.0.0.1:6379> set a 1OK127.0.0.1:6379> watch aOK127.0.0.1:6379> multi OK127.0.0.1:6379> incr aQUEUED127.0.0.1:6379> exec1) (integer) 2
127.0.0.1:6379> get a"2"

Example of failure, from the end it can be seen that the value of test was modified by other connections:

127.0.0.1:6379> set test 1OK127.0.0.1:6379> watch testOK127.0.0.1:6379> multiOK127.0.0.1:6379> incrby test 11QUEUED127.0.0.1:6379> exec(nil)
127.0.0.1:6379> get test"100"

How to solve the problem

redis The command in is atomic, so when the value is an Arabic numeral, I can change the get and set commands to incr or incrby to solve this problem. The following code enables two terminals to be executed at the same time. The result is that we Expected 2000.

<?phprequire "vendor/autoload.php";$client = new Predis\Client([
&#39;scheme&#39; => &#39;tcp&#39;,
&#39;host&#39; => &#39;127.0.0.1&#39;,
&#39;port&#39; => 6379,]);for ($i = 0; $i < 1000; $i++) { $client->incr("name");
$client->expire("name", 10800);
usleep(10000);}

It is indeed feasible and the effect is not bad. Here is an example

<?phprequire "vendor/autoload.php";$client = new Predis\Client([
&#39;scheme&#39; => &#39;tcp&#39;,
&#39;host&#39; => &#39;127.0.0.1&#39;,
&#39;port&#39; => 6379,]);class RedisLock{ public $objRedis = null;
public $timeout = 3;
/** * @desc 设置redis实例 * * @param obj object | redis实例 */
public function __construct($obj)
{ $this->objRedis = $obj;
} /** * @desc 获取锁键名 */
public function getLockCacheKey($key)
{ return "lock_{$key}";
} /** * @desc 获取锁 * * @param key string | 要上锁的键名 * @param timeout int | 上锁时间 */
public function getLock($key, $timeout = NULL)
{ $timeout = $timeout ? $timeout : $this->timeout;
$lockCacheKey = $this->getLockCacheKey($key);
$expireAt = time() + $timeout;
$isGet = (bool)$this->objRedis->setnx($lockCacheKey, $expireAt);
if ($isGet) { return $expireAt;
} while (1) { usleep(10);
$time = time();
$oldExpire = $this->objRedis->get($lockCacheKey);
if ($oldExpire >= $time) { continue;
} $newExpire = $time + $timeout;
$expireAt = $this->objRedis->getset($lockCacheKey, $newExpire);
if ($oldExpire != $expireAt) { continue;
} $isGet = $newExpire;
break;
} return $isGet;
} /** * @desc 释放锁 * * @param key string | 加锁的字段 * @param newExpire int | 加锁的截止时间 * * @return bool | 是否释放成功 */
public function releaseLock($key, $newExpire)
{ $lockCacheKey = $this->getLockCacheKey($key);
if ($newExpire >= time()) { return $this->objRedis->del($lockCacheKey);
} return true;
}
}$start_time = microtime(true);$lock = new RedisLock($client);$key = "name";for ($i = 0; $i < 10000; $i++) { $newExpire = $lock->getLock($key);
$num = $client->get($key);
$num++;
$client->set($key, $num);
$lock->releaseLock($key, $newExpire);}$end_time = microtime(true);echo "花费时间 : ". ($end_time - $start_time) . "\n";

Execute shell php setnx.php & php setnx.php&, and you will finally get the result:

$ 花费时间 : 4.3004920482635
[2] + 72356 done php setnx.php# root @ ritoyan-virtual-pc in ~/PHP/redis-high-concurrency [20:23:41] $ 花费时间 : 4.4319710731506
[1] + 72355 done php setnx.php

Similarly loop 1w times, remove usleep, and use incr to increase directly, which takes about 2 seconds.

When canceling usleep when obtaining the income, the time not only does not decrease, but increases. The setting of usleep must be reasonable to prevent the process from making useless loops

Summary

To summarize briefly, in fact, redis does not have concurrency problems, because it is a single process, and no matter how many commands are executed, they are executed one by one. When we use it, concurrency problems may occur, such as the pair of get and set.

The above is the detailed content of What is the maximum concurrency of redis?. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Redis: Beyond SQL - The NoSQL PerspectiveRedis: Beyond SQL - The NoSQL PerspectiveMay 08, 2025 am 12:25 AM

Redis goes beyond SQL databases because of its high performance and flexibility. 1) Redis achieves extremely fast read and write speed through memory storage. 2) It supports a variety of data structures, such as lists and collections, suitable for complex data processing. 3) Single-threaded model simplifies development, but high concurrency may become a bottleneck.

Redis: A Comparison to Traditional Database ServersRedis: A Comparison to Traditional Database ServersMay 07, 2025 am 12:09 AM

Redis is superior to traditional databases in high concurrency and low latency scenarios, but is not suitable for complex queries and transaction processing. 1.Redis uses memory storage, fast read and write speed, suitable for high concurrency and low latency requirements. 2. Traditional databases are based on disk, support complex queries and transaction processing, and have strong data consistency and persistence. 3. Redis is suitable as a supplement or substitute for traditional databases, but it needs to be selected according to specific business needs.

Redis: Introduction to a Powerful In-Memory Data StoreRedis: Introduction to a Powerful In-Memory Data StoreMay 06, 2025 am 12:08 AM

Redisisahigh-performancein-memorydatastructurestorethatexcelsinspeedandversatility.1)Itsupportsvariousdatastructureslikestrings,lists,andsets.2)Redisisanin-memorydatabasewithpersistenceoptions,ensuringfastperformanceanddatasafety.3)Itoffersatomicoper

Is Redis Primarily a Database?Is Redis Primarily a Database?May 05, 2025 am 12:07 AM

Redis is primarily a database, but it is more than just a database. 1. As a database, Redis supports persistence and is suitable for high-performance needs. 2. As a cache, Redis improves application response speed. 3. As a message broker, Redis supports publish-subscribe mode, suitable for real-time communication.

Redis: Database, Server, or Something Else?Redis: Database, Server, or Something Else?May 04, 2025 am 12:08 AM

Redisisamultifacetedtoolthatservesasadatabase,server,andmore.Itfunctionsasanin-memorydatastructurestore,supportsvariousdatastructures,andcanbeusedasacache,messagebroker,sessionstorage,andfordistributedlocking.

Redis: Unveiling Its Purpose and Key ApplicationsRedis: Unveiling Its Purpose and Key ApplicationsMay 03, 2025 am 12:11 AM

Redisisanopen-source,in-memorydatastructurestoreusedasadatabase,cache,andmessagebroker,excellinginspeedandversatility.Itiswidelyusedforcaching,real-timeanalytics,sessionmanagement,andleaderboardsduetoitssupportforvariousdatastructuresandfastdataacces

Redis: A Guide to Key-Value Data StoresRedis: A Guide to Key-Value Data StoresMay 02, 2025 am 12:10 AM

Redis is an open source memory data structure storage used as a database, cache and message broker, suitable for scenarios where fast response and high concurrency are required. 1.Redis uses memory to store data and provides microsecond read and write speed. 2. It supports a variety of data structures, such as strings, lists, collections, etc. 3. Redis realizes data persistence through RDB and AOF mechanisms. 4. Use single-threaded model and multiplexing technology to handle requests efficiently. 5. Performance optimization strategies include LRU algorithm and cluster mode.

Redis: Caching, Session Management, and MoreRedis: Caching, Session Management, and MoreMay 01, 2025 am 12:03 AM

Redis's functions mainly include cache, session management and other functions: 1) The cache function stores data through memory to improve reading speed, and is suitable for high-frequency access scenarios such as e-commerce websites; 2) The session management function shares session data in a distributed system and automatically cleans it through an expiration time mechanism; 3) Other functions such as publish-subscribe mode, distributed locks and counters, suitable for real-time message push and multi-threaded systems and other scenarios.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools