介绍thinkphp lock锁的使用和例子
2022-11-24 11:02:51
176
{{single.collect_count}}
下面由thinkphp教程栏目给大家介绍thinkphp lock锁的使用和例子,希望对需要的朋友有所帮助!

php入门到就业线上直播课:进入学习
Apipost = Postman + Swagger + Mock + Jmeter 超好用的API调试工具:点击使用

在开发需求中会遇到这样一种情况,并发请求。数据库的更新还没执行结束,另一个select查出的数据,会是更新之前的数据,那就会造成查询数据不准确。

那怎么解决呢?用innoDB的事务和锁就能解决这个问题。在我们当前行更新还没结束的时候,select查询此行的数据会被锁起来。

比如我们数据库有这样两行数据
在这里插入图片描述
我们把id=1的num数据更新为1000,sleep10秒,这时候我们select id=1的数据时,会等待update的更新结束,如果我们select id=2的时候,不需要等待10秒,会立马获取到数据。
这就是InnoDB的行锁,只会锁当前update的那行数据,不会锁整表。
下面会列出测试代码,记得吧引擎改为innoDB,不是MYISAM。

class Index extends Controller{public function index(){$model=Db::name('test');$model->startTrans();try{$list=$model->lock(true)->find();$model->where(['id'=>1])->data(['num'=>900])->update();//id为1的更新sleep(10);//等待10秒$model->commit();print_r($list);}catch (\Exception $exception){$model->rollback();throw $exception;}}public function index2(){$model=Db::name('test');$model->startTrans();try{$list=$model->lock(true)->where(['id'=>1])->find();//id为1在更新时,select id=1 会等待。把ID改为2时,不等待$model->commit();print_r($list);}catch (\Exception $exception){$model->rollback();throw $exception;}}}
登录后复制

测试步骤:请求index后,在请求index2,就会看到index2会等index加载结束,我们才能看到index2的打印结果。如果index2的id改为2后,则不会受到index的影响。

相关推荐:最新的10个thinkphp视频教程

以上就是介绍thinkphp lock锁的使用和例子的详细内容,更多请关注php中文网其它相关文章!

回帖
全部回帖({{commentCount}})
{{item.user.nickname}} {{item.user.group_title}} {{item.friend_time}}
{{item.content}}
{{item.comment_content_show ? '取消' : '回复'}} 删除
回帖
{{reply.user.nickname}} {{reply.user.group_title}} {{reply.friend_time}}
{{reply.content}}
{{reply.comment_content_show ? '取消' : '回复'}} 删除
回帖
收起
没有更多啦~
{{commentLoading ? '加载中...' : '查看更多评论'}}