Home >PHP Framework >ThinkPHP >How thinkphp uses redis to control concurrency

How thinkphp uses redis to control concurrency

藏色散人
藏色散人forward
2021-01-05 17:01:173206browse

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:he

qq:760863706
tp:3.2.3
date:2018 -10-19

The 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.

##

/**
*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(&#39;queue&#39;);//自增
        if ($redis->get(&#39;clock&#39;) == $random) {//当clock值满足条件
            $redis->del(&#39;clock&#39;);//删除$random随机数
        }
        $process = &#39;处理具体的业务逻辑中,耗时不定,当前时间戳:&#39;.time();

        $endRandom = mt_rand();//随机数
        $end = $redis->set(&#39;clock&#39;, $endRandom, array(&#39;nx&#39;, &#39;ex&#39; => 10));//redis加锁,锁有效期10秒
        while (!$end) 
        {
            usleep(100000);//沉睡100毫秒
            $end = $redis->set(&#39;clock&#39;, $endRandom, array(&#39;nx&#39;, &#39;ex&#39; => 10));//redis加锁,锁有效期10秒
        }
        $redis->decr(&#39;queue&#39;);//自减
        if ($redis->get(&#39;clock&#39;) == $endRandom) {//当clock值满足条件
            $redis->del(&#39;clock&#39;);//删除$endRandom随机数
        }
        return $process;
    }else{
        if ($redis->get(&#39;clock&#39;) == $random) {
            $redis->del(&#39;clock&#39;);
        }
        usleep(200000);//沉睡200毫秒
        concurrence();//递归再次调用
    }

}

In the controller, call public functions and handle related business

For more programming-related knowledge, please visit:

Programming Teaching

! !

The 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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete