class LockUtil { private static $lock_prefix = 'hi_box_lock_'; /** * @param $key * @param string $func 操作方法 * @param int $timeout * @return bool true 未锁 false 已锁 */ public static function onLock($key, $func='default', $timeout = 5): bool { if (empty($key) || $timeout <= 0) { return true; } /** * @var $redis Redis */ $redis = Cache::store('redis')->handler(); $key = self::$lock_prefix.md5($func) . $key; // $key 如果存在 设置nx后 是不会重新覆盖set return $redis->set($key, 1, ['nx', 'ex' => $timeout]); } public static function unLock($key,$func='default') { /** * @var $redis Redis */ $redis = Cache::store('redis')->handler(); $key = self::$lock_prefix .md5($func). $key; //监听Redis key防止【解锁事务执行过程中】被修改或删除,提交事务后会自动取消监控 $redis->watch($key); if ($redis->get($key)) { $redis->multi()->del($key)->exec(); } $redis->unwatch(); } }
以上就是php中redis锁怎么应用的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号