tp5 lock的使用

首先我们了解一下数据库的锁,数据库是一个多用户使用的共享资源。当多个用户并发地存取数据时,在数据库中就会产生多个事务同时存取同一数据的情况。若对并发操作不加控制就可能会读取和存储不正确的数据,破坏数据库的一致性,

注意事项:首先,数据库类型要是InnoDB,其次,加锁必须跟事务同时使用)。

在tp5中如何使用:请看以下代码

public function testTrans(){
    $time = date('H:i:s');
    $model = new appmodelStudent();
    $model->startTrans();//开启事务
    try{
        $student = $model->lock(true)->where('id', 4)->find();//加锁
        $student->update(['age' => $student['age']+10], ['id' => 4]);
        sleep(20);
        $model->commit();//事务提交
        return $time.'_lock_true_'.date('H:i:s');
    } catch (Exception $e) {
        $model->rollback();
        throw $e;
    }
    return $time.'_lock_false_'.date('H:i:s');
}

InnoDB 预设是Row-Level Lock (行级锁),FOR UPDATE 需要指定明确的主键才会行级锁,否则为表级锁,如:

select from user where id = 1 (行级锁)

select from user where id > 1 (表级锁)

操作完成后无需手动解锁,会自动解锁

参考链接:http://www.thinkphp.cn/topic/46363.html

原文地址:https://www.cnblogs.com/ivy-zheng/p/12109262.html