可能的重复:
在 PHP 中缓存对象而不使用序列化
所以我构建了一个相当大的无法轻易转换为关系数据库格式的数据结构。使用这种数据结构,我发出的请求非常快,但加载到内存中大约需要 4-5 秒。我想要的是将其加载到内存中一次,然后将其放在那里并能够快速响应各个请求,这当然不是我通常编写的 php 脚本的正常流程。在php中有什么好的方法可以做到这一点吗? (同样不使用数据库,它必须使用这种专门的预计算结构,这需要很长时间才能加载到内存中。)
编辑:本教程 提供了我想要的内容,但它非常复杂,我希望有人能有一个更优雅的解决方案。正如他在教程中所说,整个问题在于 php 自然是无状态的。
Possible Duplicate:
Cache Object in PHP without using serialize
So I have built a rather large data structure which cannot easily be turned into a relational database format. Using this data structure the requests I make are very fast but it takes about 4-5 seconds to load into memory. What I want is to load it into memory once, then have it sit there and be able to quickly answer individual requests which of course is not the normal flow with the php scripts I have written normally. Is there any good way to do this in php? (again no using a database, it has to use this specialized precomputed structure which takes a long time to load into memory.)
EDIT: This tutorial kind of gives what I want but it is pretty complicated and I was hoping someone would have a more elegant solution. As he says in the tutorial the whole problem is that naturally php is stateless.
发布评论
评论(1)
您绝对必须执行链接教程建议的操作。
请求之间不会保留 PHP 状态。这是设计使然。
因此,您将需要某种单独的长时间运行的进程,从而需要某种 IPC 方法,否则您需要一个可以分段加载的更好的数据结构。
如果你确实无法将其放入关系数据库(例如
sqlite
——它不必是进程数据库),探索使用其他类型的数据库,例如
基于文件的键值存储
。请注意,您用任何语言编写的任何长时间运行的过程都极不可能会比将您的数据结构放入真正的数据库(关系数据库或其他数据库)更快、更容易或更好!将您的数据结构放入数据库!这是您可能的路径中最简单的。
您可以做的另一件事是尽可能快地加载数据结构。可以将其序列化为文件,然后反序列化该文件;如果这还不够快,你可以尝试 igbinary,它比标准 php 快得多序列化器。
You absolutely must do something like what your linked tutorial proposes.
No PHP state persist between requests. This is by design.
Thus you will need some kind of separate long-running process and thus some kind of IPC method, or else you need a better data structure you can load piecemeal.
If you really can't put this into a relational database (such as
sqlite
--it doesn't have to be a process database), explore using some other kind of database, such as afile-based key-value store
.Note that it is extremely unlikely that any long-running process you write, in any language, will be faster, easier, or better than getting this data structure of yours into a real database, relational or otherwise! Get your data structure into a database! It's the easiest among your possible paths.
Another thing you can do is just make loading your data structure as quick as possible. You can serialize it to a file and then deserialize the file; if that is not fast enough you can try igbinary, which is a much-faster-than-standard-php serializer.