如何在php/mysql Web应用程序中实现悲观锁定?

问题描述:

如何在php/mysql Web应用程序中实现悲观锁定?

How to implement pessimistic locking in a php/mysql web application?

  1. 网络用户打开一个页面来编辑一个数据集(行)
  2. 网络用户单击锁定"按钮,因此其他用户可以读取但不能写入此数据集
  3. 网络用户进行了一些修改(可能需要1到30分钟)
  4. 网络用户点击保存"或取消",然后删除锁定"

在这种情况下,php/mysql中是否有标准方法?如果网络用户从不单击保存"/取消",而是关闭了Internet Explorer,会发生什么?

Are there standard methods in php/mysql for this scenario? What happens if the web-user never clicks on "save"/"cancel" but closes the internet-exploror?

传统上,这是通过对数据库中记录的布尔locked列进行适当标记的来完成的.

Traditionally this is done with a boolean locked column on the record in the database that is flagged appropriately.

这种锁定的功能是必须释放该锁定,并且情况可能会自然地阻止这种情况发生(系统崩溃,用户愚蠢,丢失的网络数据包等).这就是为什么您需要提供一些手动解锁方法和/或对记录锁定多长时间施加时间限制(也许有cron作业?)的原因.如果浏览器仍处于打开状态,您可以实施某种AJAX轮询来保持记录锁定?无论如何,您最好在修改锁之前先验证记录中的数据是否与获取锁时的数据相同.

It is a function of this sort of locking that the lock has to be released, and circumstances may prevent this happening naturally (system crashes, user stupidity, dropped network packets, etc etc etc). This is why you would need to provide some manual unlock method and/or impose a time limit (maybe with a cron job?) on how long a record can be locked for. You could implement some kind of AJAX poll to keep the record locked if the browser is still open? At any rate, you would probably be best to verify the data in the record is the same as it was when the lock was aquired before you modify it.

这种行为的限制在Web应用程序中尤为普遍,但使用这种方法的任何事物都是如此-Sage Line 50就是一个麻烦,我经常必须在计算机/应用程序崩溃.

This limitation of this type of behaviour is particularly prevalent in web applications, but is true of anything that uses this approach - Sage Line 50, for one, is a bugger for it, I regularly have to delete lock files after machine/application crashes.