redis; $hasWait = 0;//已经等待的时间:毫秒 while(true){ $res = $redis->set($key,$identification,'NX','EX',$expire); if ($res){ return true; break; }else{ if($hasWait > $wait_time*1000){ //等待超时 return false; } //sleep(10); usleep(300 * 1000);//等待300ms $hasWait += 300; continue; } } return false; } /** * 解锁 * @param $key * @param $identification */ public static function uLock($key,$identification){ $redis = \Yii::$app->redis; $script = ' if redis.call("get",KEYS[1]) == ARGV[1] then return redis.call("del",KEYS[1]) else return 0 end'; $redis->eval($script,1,$key,$identification); } /** * 批量解锁 * @DateTime 2021-11-10 17:06:37 * @copyright: Copyright (c) 2020 广东七件事集团 * @param [type] $lock_arr[$key=>$identification] * @return void */ public static function batchUlock($lock_arr){ foreach($lock_arr as $key => $identification){ self::uLock($key,$identification); } } /** * @desc:阻塞读锁 * @Author: hua * @Date: 2021/12/3 * @Time: 19:24 * @Copyright: copyright (c) 2021 广东七件事集团 * @param $key * @param $wait_time * @return bool */ public static function readLock($key,$wait_time = 30){ $redis = \Yii::$app->redis; $hasWait = 0;//已经等待的时间:毫秒 while(true){ $res = $redis->get($key); if (!$res){ return true; break; }else{ if($hasWait >= $wait_time*1000){ //等待超时 return false; } usleep(300 * 1000);//等待300ms $hasWait += 300; continue; } } return false; } /** * 获取频繁锁使用Key * * @param string $key * @return string */ protected static function getFkey(string $key) { return sprintf('fff%s', $key); } /** * Redis频繁锁 * 使用Lua脚本设置一个过期值 * 解锁可以使用unFLock * 返回false时候为可以继续执行, 返回true需要返回停止程序返回繁忙信息 * 使用方式 * * if (LockHelper::fLock($key, $seconds)) return $this->error('忙碌'); * ---业务逻辑--- * static::unFLock($key); * * @param string $key * @param integer $seconds 正常操作5秒锁够用 如果业务逻辑比较慢可以增加锁的时间 * @return boolean */ public static function fLock(string $key, int $seconds = 5) { $redis = \Yii::$app->redis; $script = <<