问题描述
我目前正在构建一个 PHP 框架(我知道是原创的)并且正在为它开发一些优化功能.我遇到的一个难题是缓存 MySQL 结果的最佳方法是什么?我知道有些人会说,首先优化你的 MySQL 等,但是为了争论,我的查询需要 1 分钟才能运行并且尽可能优化.
I am currently building a PHP framework (original, i know) and im working on some optimisation features for it. One dilema I have come accross is what is the best way to cache MySQL results? I know some people will say, first optimise your MySQL etc, but lets say for arguments sake, my query takes 1 minute to run and is as optimised as possible.
在 PHP 中缓存结果的最佳方法是什么,这样我就不必在每次加载页面时都重新运行查询?
What would be the best way to cache the results in PHP so I dont have to rerun the query every page load?
我的第一个想法是循环遍历结果,将它们添加到一个数组中...序列化它们然后存储在一个文件中.现在创建缓存只发生一次,如果数组包含 100 万个结果,我可以负担序列化函数的开销.但是,加载缓存文件,然后在每次页面加载时反序列化数组,可能会影响性能.
My first thought was to maybe loop through the results, add them to an array... serialize them and then store in a file. Now as creating the cache only occurs once, I can afford the overhead of the serialize function if the array contains say 1 million results. How ever, loading the cached file and then unserializing the array on every pageload, could have performance impact.
在缓存时,而不是序列化结果和写入文件,以一种在 PHP 可读数组中显示结果的方式写入文件会是一个更好的主意.所以当它加载时,没有反序列化开销.
Would it then be a better idea to while caching, instead of serializing the results and the writing to file, write to the file in a way that displays the results in a PHP readable array. So when it loads, there is no unserialize overhead.
是否有其他(读取:更快)方法来缓存一个经常使用的慢查询?
Are there any other (read: faster) ways to cache a slow query for frequent use?
推荐答案
如果这是一个直数组,那么你可以使用 var_export() 而不是序列化(用适当的 "" 包装它并将其写入 .php 文件;然后 include() 在你的脚本中.如果你能把它写在 htdocs 树之外,并且只真正适用于内存缓存会认为过多的大量数据,那就最好了.
If this is a straight array, then you could use var_export() rather than serialize (wrapping it with the appropriate "" and write it to a .php file; then include() that in your script. Best done if you can write it outside the htdocs tree, and only really appropriate for large volumes of data that memory caches would consider excessive.
这篇关于PHP 缓存 MySQL 结果的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!