Using Php+mysql to do an internal use of small tools, that is, the user has a user name, login success, go to the server to request data, the characteristics of the request data is that the database of a table
status = 0
A data, the code is probably written like this:
'select * from dir where status = 0 limit 1'
After the request succeeds, status
set it to-1, but when the user initiates the request at the same time, often appear request the same data situation, this situation how can be relatively fast resolution? Database lock? More urgent--new contact with the web--
Reply content:
Using Php+mysql to do an internal use of the gadget, that is, the user has a user name, login success, go to the server to request data, request data is characterized by a database of a table of status = 0
data, the code is probably written like this:
'select * from dir where status = 0 limit 1'
After the request succeeds, status
set it to-1, but when the user initiates the request at the same time, often appear request the same data situation, this situation how can be relatively fast resolution? Database lock? More urgent--new contact with the web--
Transaction
Add pessimistic lock for update when Select
Show Code
begin$id = select id from table where status=0 for update;xxxxxxTODO SOMETHINGxxxxxupdate table set status=1 where id=$id;commit
Upstairs "Big Uncle" said the support business class engine (such as InnoDB) solution, for MyISAM is no solution.
Since it's just an internal gadget, let me take a simple approach:
If it is just a single piece of data, update the process first, and the process fails to roll back. Such as
UPDATE `dir` SET `status`=-1 WHERE `status`=0# 这样条件合理的话只有一个请求会更新成功,返回1,其余请求返回0更新失败。# 继续原来的逻辑,如果原来的逻辑处理不通过则将status更新回0,这样有点类似于一个锁
If this is a large amount of data, the first request arrives with a file lock (for example, an empty piece of xxx.lock) to check the database, checks for the existence of the file lock before each request, and cancels the request if it already exists.