Yii源码解析之MysqlMutex

版权声明:转载请注明来源 https://blog.csdn.net/u013702678/article/details/84261269

基于Mysql实现的锁,其原理是利用了mysql提供的API,即:

select get_lock(key, timeout) from ***; 

select release_lock(key) from ***;

其中***为要加锁的KEY。
class MysqlMutex extends DbMutex
{
    /**
     * Initializes MySQL specific mutex component implementation.
     * @throws InvalidConfigException if [[db]] is not MySQL connection.
     */
    public function init()
    {
        parent::init();
        if ($this->db->driverName !== 'mysql') {
            throw new InvalidConfigException('In order to use MysqlMutex connection must be configured to use MySQL database.');
        }
    }

    /**
     * Acquires lock by given name.
     * @param string $name of the lock to be acquired.
     * @param int $timeout time (in seconds) to wait for lock to become released.
     * @return bool acquiring result.
     * @see http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_get-lock
     */
    protected function acquireLock($name, $timeout = 0)//创建锁SQL,执行查询
    {
        return $this->db->useMaster(function ($db) use ($name, $timeout) {
            /** @var \yii\db\Connection $db */
            return (bool) $db->createCommand(
                'SELECT GET_LOCK(:name, :timeout)',
                [':name' => $name, ':timeout' => $timeout]
            )->queryScalar();
        });
    }

    /**
     * Releases lock by given name.
     * @param string $name of the lock to be released.
     * @return bool release result.
     * @see http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
     */
    protected function releaseLock($name)//创建释放锁SQL,执行查询
    {
        return $this->db->useMaster(function ($db) use ($name) {
            /** @var \yii\db\Connection $db */
            return (bool) $db->createCommand(
                'SELECT RELEASE_LOCK(:name)',
                [':name' => $name]
            )->queryScalar();
        });
    }
}

猜你喜欢

转载自blog.csdn.net/u013702678/article/details/84261269
今日推荐