How thinkphp uses redis to control concurrency
The following thinkphp framework tutorial column will introduce to you how thinkphp uses redis to control concurrency. I hope it will be helpful to friends in need!
##author:heThe project developed by the tp framework needs to control the access volume of a certain business at the same time. It uses the redis lock mechanism to achieve the purpose and creates a public function concurrence# in the tp public method.qq:760863706
tp:3.2.3
date:2018 -10-19
##
/** *redis控制并发 **/ function concurrence(){ //实例化redis $redis = new \Redis(); $redis->connect(C('REDIS_HOST'),C('REDIS_PORT')); $redis->auth(C('REDIS_AUTH')); //进入队列及出列,queue在加减的时候,要保证操作的唯一性,此时加锁,完成后在解锁 $random = mt_rand();//生成随机数 $start = $redis->set('clock', $random, array('nx', 'ex' => 10));//redis加锁,锁有效期10秒 while (!$start) { usleep(100000);//沉睡100毫秒 $start = $redis->set('clock', $random, array('nx', 'ex' => 10));//redis加锁,锁有效期10秒 } $queue = $redis->get('queue'); if ($queue <= 10) { $redis->incr('queue');//自增 if ($redis->get('clock') == $random) {//当clock值满足条件 $redis->del('clock');//删除$random随机数 } $process = '处理具体的业务逻辑中,耗时不定,当前时间戳:'.time(); $endRandom = mt_rand();//随机数 $end = $redis->set('clock', $endRandom, array('nx', 'ex' => 10));//redis加锁,锁有效期10秒 while (!$end) { usleep(100000);//沉睡100毫秒 $end = $redis->set('clock', $endRandom, array('nx', 'ex' => 10));//redis加锁,锁有效期10秒 } $redis->decr('queue');//自减 if ($redis->get('clock') == $endRandom) {//当clock值满足条件 $redis->del('clock');//删除$endRandom随机数 } return $process; }else{ if ($redis->get('clock') == $random) { $redis->del('clock'); } usleep(200000);//沉睡200毫秒 concurrence();//递归再次调用 } }
In the controller, call public functions and handle related business
For more programming-related knowledge, please visit:
Programming TeachingThe above is the detailed content of How thinkphp uses redis to control concurrency. For more information, please follow other related articles on the PHP Chinese website!

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
