简体   繁体   English

如何防止在线酒店预订中的竞争条件

[英]How to prevent race condition in online hotel booking

I am writing a hotel booking software using PHP and MySQL.我正在使用 PHP 和 MySQL 编写酒店预订软件。 I am pretty much done with it but I ran into a race condition problem.我差不多完成了,但我遇到了竞争条件问题。 For example there is only one standard room left and when 2 guests both select it it shows available to both of them.例如,只剩下一个标准间,当 2 位客人都选择它时,它会显示可供他们使用。 I tried fixing it by checking the room again when the guest clicks confirm before payment but that still has issues.当客人在付款前点击确认时,我尝试通过再次检查房间来修复它,但仍然存在问题。 I also tried making the room status to pending when whoever clicks the confirm first but I can't figure out how to change it back to available if the guest decides not to pay or just closes the browser.我还尝试在谁先点击确认时将房间状态设置为待定,但如​​果客人决定不付款或只是关闭浏览器,我无法弄清楚如何将其更改回可用状态。 I searched SO for answers but I didn't really find a definitive answer.我搜索了SO寻找答案,但我并没有真正找到明确的答案。 Thanks in advance提前致谢

One solution is to add two columns to a table in the database.一种解决方案是向数据库中的表添加两列。 One column is the session ID or user ID or whatever of the user that is being offered the room.一列是会话 ID 或用户 ID 或被提供房间的任何用户。 The second column is a timestamp indicating when that offer will expire.第二列是一个时间戳,指示该优惠何时到期。

Then, in your app, only show rooms that have an expired timestamp in the hold column.然后,在您的应用中,仅显示保留列中具有过期时间戳的房间。 (Set the initial timestamp to 0 so that it starts out expired.) When a room is selected, check the column again. (将初始时间戳设置为 0,使其开始时已过期。)选择房间后,再次检查该列。 If there's an unexpired timestamp there, the user gets a "sorry, you were too slow" message.如果那里有一个未过期的时间戳,用户会收到一条“对不起,你太慢了”的消息。 Otherwise, put a timestamp there for 15 minutes into the future or whatever, and proceed.否则,将时间戳放在未来 15 分钟之内,然后继续。

You see this on travel sites and ticket-purchasing sites a lot where it says something like "We're holding these seats for you for another 14 minutes. Please complete the transaction by then or it will be released blah blah blah."你在旅游网站和购票网站上经常看到这样的话,上面写着“我们为你保留这些座位 14 分钟。请到那时完成交易,否则它会被释放等等。”

I would also go with the pending state.我也会选择挂起状态。 You could save the state together with the session id of this user and have a cronjob that deletes all pending states that have expired session ids associated to them.您可以将状态与该用户的会话 ID 一起保存,并有一个 cronjob 来删除所有与它们相关联的会话 ID 已过期的挂起状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM