乐观和悲观锁 [英] optimistic and pessimistic locks

查看:88
本文介绍了乐观和悲观锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用我的第一个php / Codeigniter项目,我已经搜索锁定访问编辑数据的信息,并没有找到很多信息。

Working on my first php/Codeigniter project and I’ve scoured the ‘net for information on locking access to editing data and haven’t found very much information.

我期望这是一个相当规律的事件,2个用户尝试同时编辑同一个表单。

I expect it to be a fairly regular occurrence for 2 users to attempt to edit the same form simultaneously.

我的经验(在BBx,filePro和其他RAD应用程序的有状态的世界)是,正在编辑的数据被锁定使用悲观锁 - 一个用户有权访问编辑表单的时候。第二个用户基本上必须等待第一个完成。我理解这可以使用Ajax发送XMLHttpRequests来维护一个'锁'数据库。

My experience (in the stateful world of BBx, filePro, and other RAD apps) is that the data being edited is locked using a pessimistic lock—one user has access to the edit form at the time. The second user basically has to wait for the first to finish. I understand this can be done using Ajax sending XMLHttpRequests to maintain a ‘lock’ database.

php世界,缺乏状态,似乎更喜欢乐观锁。如果我正确理解它的工作原理是这样的:两个用户都访问数据,他们每个记录一个前更改版本的数据。在保存更改之前,将再次检索数据并比较之前更改版本。如果两个版本相同,则写入用户更改。如果他们不同;用户显示自他/她开始编辑之后发生了变化,并且添加了一些机制以解决差异 - 或者用户被显示为对不起,再试一次消息。

The php world, lacking state, seems to prefer optimistic locking. If I understand it correctly it works like this: both users get to access the data and they each record a ‘before changes’ version of the data. Before saving their changes, the data is once again retrieved and compared the ‘before changes’ version. If the two versions are identical then the users changes are written. If they are different; the user is shown what has changed since he/she started editing and some mechanism is added to resolve the differences—or the user is shown a ‘Sorry, try again’ message.

我对这里的人们实施悲观和乐观锁定感到兴趣。如果有任何库,工具或如何可用,我感谢一个链接。

I’m interested in any experience people here have had with implementing both pessimistic and optimistic locking. If there are any libraries, tools, or ‘how-to’s available I’m appreciate a link.

感谢

推荐答案

据我所知,CodeIgniter没有支持锁定行。
如果要实现乐观锁定,应该添加一个版本列或时间戳列,您必须在每次更新/插入时更改该列。将版本列放入表单中的隐藏字段。然后在每次更新之前,添加一个where子句,如:

As far as I know, CodeIgniter has no support of locking rows. If you want to implement optimistic locking, you should add a version column or timestamp column that is you must change on each update/insert. Put the version column into a hidden field in your forms. Then before each update, add a where clause like :

$this->db->where('version',$editedVersion);

$this->db->where('timestamp',$editedTimestamp);

然后你应该检查更新是否正确更新1行..

And then you should check that the update correctly updated 1 rows..

$this->db->where('id',$editedId);
$this->db->update('tablename',$data);
$rowsAffected = $this->db->affected_rows();
if ($rowsAffected == 0) {
    /* Data changed by other user, update failed */
} else {
   /* updated successfully */
}

这篇关于乐观和悲观锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆