PHP 中的并发写入?
我有一个 fwrite 函数来写入延迟插入数据库的日志。
我们的访问率为每小时 20,000 次访问。
所以每次写入时间为 0.18 秒。
我的问题是,当有2个或3个访客同时进来时,PHP是否可能会错过多个日志?
如果是的话我怎样才能使其并发?
我的代码只是普通的 Fopen fwrite fclose 。
I have a fwrite function to write log for delay insert to the database.
We have a visit rate of 20,000 Visits per hour.
so it's 0.18s per fwrite.
My question is that is it possible that PHP will miss several log when there are 2 or 3 visitor come in at the same time?
If it's then how can I make this concurrent?
My code is just normal Fopen fwrite fclose.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我是你,我会避免这种情况。如果您必须为每个请求记录一些内容,请使用 Gearman 之类的工具将数据排队以供以后处理,或者将其存储在数据库(或 NoSQL 数据库)中以供以后处理。不要忘记数据库就是为了解决这个问题而设计的。不要尝试使用日志文件重新发明数据库。
更不用说每次写入 0.18 秒可能比插入 DBM 昂贵得多(对我来说,MySQL 通常会在 0.01 秒内返回写入,具体取决于表,MongoDB 可能要快得多)。
I would avoid this if I was you. If you must log something for each request, either use something like Gearman to queue the data for later processing, or store it in a database (or a NoSQL db) for later processing. Don't forget that databases were designed to solve this very problem. Don't try to re-invent a db using log files.
Not to mention that 0.18s per write is likely a lot more expensive than an insert into a DBM (MySQL for me typically returns writes inside of 0.01 seconds, depending on the table, MongoDB can be a LOT faster).
你如何触发写入?如果每个请求(每次访问 1 个)都有关联的 fwrite,那么您将不会错过任何请求。也许它们可能会变得很慢,因为您的 Web 服务器正在排队/处理请求(峰值流量),但 PHP 是请求驱动的,因此对于每个页面加载,您都会执行 fwrite。
我说你不会错过任何一个,因为除非你执行一些非阻塞 I/O,否则你的脚本将阻塞 fwrite 调用。换句话说,fwrite 将执行。
如果不做一些真正时髦的事情,您将很难在用 PHP 编写的请求驱动应用程序上获得任何类型的并发性。
How are you firing off the writes? If each requests (1 per visit) has an associated fwrite with it, you won't miss any. Perhaps they could become slow(er) as your web server is queuing / handling requests (peak traffic), but PHP is request driven, so for every page load, you'll have the fwrite execute.
I say you won't miss any because, unless your doing some non blocking I/O, your script is going to block on the fwrite call. In other words, fwrite will execute.
You're going to have trouble getting any sort of concurrency on a request driven app written in PHP without doing some really funky stuff.