The problem of high concurrency is a problem we often encounter, so how to solve the problem of high concurrency? This article introduces the use of Redis locks to solve high concurrency problems. Let’s take a look.
Here we mainly use the setnx command of Redis to handle high concurrency.
setnx has two parameters. The first parameter represents the key. The second parameter represents the value. If the current key does not exist, the current key will be inserted, using the second parameter as the value. Return 1. If the current key exists, 0 will be returned.
Create inventory table
CREATE TABLE `storage` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `number` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1
Set the initial inventory to 10
Create order table
CREATE TABLE `order` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `number` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1
When testing without locks
$pdo = new PDO('mysql:host=127.0.0.1;dbname=test', 'root', 'root'); $sql="select `number` from storage where id=1 limit 1"; $res = $pdo->query($sql)->fetch(); $number = $res['number']; if($number>0) { $sql ="insert into `order` VALUES (null,$number)"; $order_id = $pdo->query($sql); if($order_id) { $sql="update storage set `number`=`number`-1 WHERE id=1"; $pdo->query($sql); } }
ab The test simulated concurrency and found that the inventory was correct.
mysql> select * from storage; +----+--------+ | id | number | +----+--------+ | 1 | 0 | +----+--------+ 1 row in set (0.00 sec)
Looking at the order table
mysql> select * from `order`; +----+--------+ | id | number | +----+--------+ | 1 | 10 | | 2 | 10 | | 3 | 9 | | 4 | 7 | | 5 | 6 | | 6 | 5 | | 7 | 5 | | 8 | 5 | | 9 | 4 | | 10 | 1 | +----+--------+ 10 rows in set (0.00 sec)
I found that there are several orders operating on the same inventory data, which may cause oversold conditions.
Modify the code and add redis lock for data control
<?php /** * Created by PhpStorm. * User: daisc * Date: 2018/7/23 * Time: 14:45 */ class Lock { private static $_instance ; private $_redis; private function __construct() { $this->_redis = new Redis(); $this->_redis ->connect('127.0.0.1'); } public static function getInstance() { if(self::$_instance instanceof self) { return self::$_instance; } return self::$_instance = new self(); } /** * @function 加锁 * @param $key 锁名称 * @param $expTime 过期时间 */ public function set($key,$expTime) { //初步加锁 $isLock = $this->_redis->setnx($key,time()+$expTime); if($isLock) { return true; } else { //加锁失败的情况下。判断锁是否已经存在,如果锁存在切已经过期,那么删除锁。进行重新加锁 $val = $this->_redis->get($key); if($val&&$val<time>del($key); } return $this->_redis->setnx($key,time()+$expTime); } } /** * @param $key 解锁 */ public function del($key) { $this->_redis->del($key); } } $pdo = new PDO('mysql:host=127.0.0.1;dbname=test', 'root', 'root'); $lockObj = Lock::getInstance(); //判断是能加锁成功 if($lock = $lockObj->set('storage',10)) { $sql="select `number` from storage where id=1 limit 1"; $res = $pdo->query($sql)->fetch(); $number = $res['number']; if($number>0) { $sql ="insert into `order` VALUES (null,$number)"; $order_id = $pdo->query($sql); if($order_id) { $sql="update storage set `number`=`number`-1 WHERE id=1"; $pdo->query($sql); } } //解锁 $lockObj->del('storage'); } else { //加锁不成功执行其他操作。 }</time>
Carry out the ab
test again and check the test results
mysql> select * from `order`; +----+--------+ | id | number | +----+--------+ | 1 | 10 | | 2 | 9 | | 3 | 8 | | 4 | 7 | | 5 | 6 | | 6 | 5 | | 7 | 4 | | 8 | 3 | | 9 | 2 | | 10 | 1 | +----+--------+ 10 rows in set (0.00 sec)
It is found that the order table does not operate the same inventory The situation of the data. Therefore, using redis lock can effectively handle high concurrency.
There is actually no need to judge the expiration time when locking. In order to avoid deadlock, we add an expiration time judgment. Actively delete the lock when it expires.
Related recommendations:
php uses file locks to solve high concurrency problems
How to use Redis to store PHP sessions Solve the problem of concurrency and consistency
The above is the detailed content of How to use Redis lock to solve high concurrency problems. For more information, please follow other related articles on the PHP Chinese website!

高并发三种解决方法是:1、系统拆分,将一个系统拆分为多个子系统;2、缓存,所有现代计算机系统发挥高性能的重要因素之一;3、MQ(消息队列),基础数据结构中的“先进先出”的一种数据机构。

随着互联网技术的迅猛发展,越来越多的应用程序需要处理大量的数据和并发访问请求。为了应对这些挑战,Go语言应运而生,成为了一种极其适合高并发和大数据处理的语言。本文将介绍Go语言中的高并发与大数据处理技术。一、高并发处理技术协程(Goroutine)Go语言中独有的一种轻量级线程实现,占用极少的内存空间和系统资源。使用协程可以轻松实现上万个并发执行的任务,具有

原因:go语言在设计的时候从关键字层面实现了多协程开发。go语言实现了CSP并发模型做为并发基础,底层使用goroutine做为并发实体,goroutine非常轻量级可以创建几十万个实体;实体间通过channel继续匿名消息传递使之解耦,在语言层面实现了自动调度,这样屏蔽了很多内部细节,对外提供简单的语法关键字,大大简化了并发编程的思维转换和管理线程的复杂性。

Swoole是一款基于PHP的高性能异步面向网络编程的框架,能够实现异步IO、多进程多线程、协程等特性,能够大幅提高PHP在网络编程方面的性能表现。在很多实时且高并发的应用场景下,Swoole已经成为了开发者的首选。本文将介绍如何使用Swoole实现高并发大文件上传的方案。一、传统方案的问题在传统的文件上传方案中,通常使用的是HTTP的POST请求方式,即将

笔者专门研究了一下“12306”的服务端架构,学习到了其系统设计上很多亮点,在这里和大家分享一下并模拟一个例子:如何在100万人同时抢1万张火车票时,系统提供正常、稳定的服务。

怎么解决高并发大流量问题?下面本篇文章就来给大家分享下高并发大流量web解决思路及方案,希望对大家有所帮助!

在互联网时代,经常会遇到需要访问大量URL的场景,如爬虫、数据采集等。传统的wget或curl工具在进行高并发访问时,很容易出现瓶颈以及性能问题。而Swoole,作为PHP的扩展模块,可以为我们提供一个高效的替代方案。Swoole是一个开源的PHP扩展,其最初的设计目的是用于构建高性能、高可伸缩性的网络服务器和Web服务。随着其不断的完善和发展,Swoole

随着互联网的飞速发展,海量的数据存储和处理已经成为企业和组织发展中的重要问题。在存储大数据的过程中,传统的单机存储技术已经无法满足高并发、高可靠性、低延迟、易扩展等实际需求。因此,分布式存储技术应运而生。Go-zero是由蚂蚁金服基于Go语言开发的分布式应用框架,具备高并发、高可靠性、低延迟、易扩展等特点。Go-zero包含了RPC框架、Web框架以及数据存


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools
