Yii乐观锁的使用及原理

来源:互联网 发布:网络维护费用清单 编辑:程序博客网 时间:2024/05/21 21:26

原理:

数据表中使用一个int类型的字段来存储版本号,即该行记录的版本号。更新数据时,对比版本号是否一致

sql查询代码如下(伪代码)

update `test_ver` set `name`="lili" and `ver`=2 where `id`=1 and `ver`=1

即在更新时的where查询条件中,带上之前查询记录时得到的版本号,如果其他线程已经修改了该记录,则版本号势必不会一致,则更新失败

示例

数据表

假设有如下数据表
数据表示意图

模型类

app\models\TestVer

该模型类,重写BaseActiveRecord类中的optimisticLock方法

声明用于记录版本号的字段

/** * 乐观锁 * @return string */public function optimisticLock(){    return 'ver';}public function updateRecord(){    $ver = self::findOne(['id'=>1]);    $ver->name = "lili";    $res = $ver->update();    return $res;}

updateRecord修改id为1的记录

控制器

控制器中调用updateRecord方法

public function actionVersion(){    $testVer = new TestVer();    $res = $testVer->updateRecord();    return $this->render('version');}

Yii Debugger结果

查看database选项,可以查看到实际执行的sql语句。
有一条语句如下

UPDATE `test_ver` SET `name`='lili', `ver`='2' WHERE (`id`='1') AND (`ver`='1')

Yii乐观锁实现原理

实现原理在yii\db\BaseActiveRecord::updateInteranl()方法

参考 http://www.digpage.com/lock.html

protected function updateInternal($attributes = null){    if (!$this->beforeSave(false)) {        return false;    }    // 获取等下要更新的字段及新的字段值    $values = $this->getDirtyAttributes($attributes);    if (empty($values)) {        $this->afterSave(false, $values);        return 0;    }    // 把原来ActiveRecord的主键作为等下更新记录的条件,    // 也就是说,等下更新的,最多只有1个记录。    $condition = $this->getOldPrimaryKey(true);    // 获取版本号字段的字段名,比如 ver    $lock = $this->optimisticLock();    // 如果 optimisticLock() 返回的是 null,那么,不启用乐观锁。    if ($lock !== null) {        // 这里的 $this->$lock ,就是 $this->ver 的意思;        // 这里把 ver+1 作为要更新的字段之一。        $values[$lock] = $this->$lock + 1;        // 这里把旧的版本号作为更新的另一个条件        $condition[$lock] = $this->$lock;    }    $rows = $this->updateAll($values, $condition);    // 如果已经启用了乐观锁,但是却没有完成更新,或者更新的记录数为0;    // 那就说明是由于 ver 不匹配,记录被修改过了,于是抛出异常。    if ($lock !== null && !$rows) {        throw new StaleObjectException('The object being updated is outdated.');    }    $changedAttributes = [];    foreach ($values as $name => $value) {        $changedAttributes[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;        $this->_oldAttributes[$name] = $value;    }    $this->afterSave(false, $changedAttributes);    return $rows;}

从上面的代码中,我们不难得出:

  • 当 optimisticLock() 返回 null 时,乐观锁不会被启用。
  • 版本号只增不减。
  • 通过乐观锁的条件有2个,一是主键要存在,二是要能够完成更新。
  • 当启用乐观锁后,只有下列两种情况会抛出 StaleObjectException 异常:
    • 当记录在被别人删除后,由于主键已经不存在,更新失败。
    • 版本号已经变更,不满足更新的第二个条件。
原创粉丝点击