Here is an example of the TP framework:
1. Use the function of MYSQL lock table
The core of this method is to lock the table and unlock:
// 这里锁定tests表
M()->execute('LOCK TABLES tests WRITE');
$data = M('tests')->find(1);
if ($data['counts'] > 0 && M('tests')->where('id=1')->setDec('counts')) {
// 抢成功了
} else {
// 抢失败了
}
// 操作完之后解开锁
M()->execute('UNLOCK TABLES');
2. Make a fuss on the SQL statement
Compared with the above method, it is more efficient (core: counts > 0 (the field to be reduced must be > 0)):
// 这里主要利用了 `counts` 字段,SQL如果有修改会返回修改的条数,当 `counts` 字段减少到 0 的时候再减就会返回修改的条数为 0 ,根据返回的修改条数的判断也能实现是否抢成功
if (M('tests')->where('id=1 and counts > 0')->setDec('counts')) {
// 抢成功了
} else {
// 抢失败了
}
Third, use redis to lock
The specific implementation method is not written here, but the general principle is:
redis
Send a lock order request to .redis
The returned result is 1, indicating that the order is locked successfully (execute business logic), and 0 indicates that it has been locked (cannot execute business logic).- After the business logic is executed, an unlock request is
redis
sent to .