Home > Database > Redis > How to apply redis lock in php

How to apply redis lock in php

王林
Release: 2023-05-27 21:49:04
forward
1384 people have browsed it

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(&#39;redis&#39;)->handler();
        $key = self::$lock_prefix.md5($func) . $key;
        // $key 如果存在 设置nx后 是不会重新覆盖set
        return $redis->set($key, 1, [&#39;nx&#39;, &#39;ex&#39; => $timeout]);
    }

    public static function unLock($key,$func=&#39;default&#39;)
    {
        /**
         * @var  $redis Redis
         */
        $redis = Cache::store(&#39;redis&#39;)->handler();
        $key = self::$lock_prefix .md5($func). $key;
        //监听Redis key防止【解锁事务执行过程中】被修改或删除,提交事务后会自动取消监控
        $redis->watch($key);
        if ($redis->get($key)) {
            $redis->multi()->del($key)->exec();
        }
        $redis->unwatch();
    }

}
Copy after login

The above is the detailed content of How to apply redis lock in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template