Query caching in php for mysql performance
Use special data caching in PHP — like memcached Use sockets instead of TCP\IP connection to database Use mysql-nd instead of mysql And here is the answer to your exact question: PHP — Is it good practice to cache MYSQL queries in a txt file? Client-side caches will be more scalable (for example, if one per web server) but less effective, and expose stale data to the application (they will probably not be automatically expired when their data become stale).
Caching MySQL queries
This is a great overview of how to cache queries in MySQL:
You can use Zend Cache to cache results of your queries among other things.
I think the query cache size is 0 by default, which is off. Edit your my.cnf file to give it at least a few megabytes. No PHP changes necessary 🙂
Php — Caching MySQL queries, lo_fye. 6,760 3 31 49. As I install mysql on many Ubuntu/Debian servers and checked they re configurations, caching is turn on by default. query_cache_limit=1M and `query_cache_size=16M’. – shgnInc. Apr 15, 2014 at 4:09. Add a comment. 1. It may be complete overkill for what you’re attempting, …
Query Caching in MySQL
You can of course use caching, but i would recommend caching the result, not the query in mysql.
But first things first, make sure that a) you have the proper indexing on your data, b) that it’s being used .
If this does not work, as group by tends to be slow with large datasets, you need to put the summary data in a static table/file/database.
There are several techniques/libraries etc that help you perform server side caching of your data. PHP Caching to Speed up Dynamically Generated Sites offers a pretty simple but self explanatory example of this.
Have you considered periodically running your long query and storing all the results in a summary table? The summary table can be quickly queried because there are no JOINs and no GROUPings. The downside is that the summary table is not up-to-the-minute current.
I realize this doesn’t address the LIMIT/OFFSET issue, but it does fix the issue of running a difficult query multiple times.
Depending on how often the data is updated, data-warehousing is a straightforward solution to this. Basically you:
- Build a second database (the data warehouse) with a similar table structure
- Optimise the data warehouse database for getting your data out in the shape you want it
- Periodically (e.g. overnight each day) copy the data from your live database to the data warehouse
- Make the page get its data from the data warehouse.
There are different optimisation techniques you can use, but it’s worth looking into:
- Removing fields which you don’t need to report on
- Adding extra indexes to existing tables
- Adding new tables/views which summarise the data in the shape you need it.
Php — Query Caching in MySQL, This is a simple query that returns 10 results, including the player_id and amount of kills each player has made: SELECT player_id, SUM (kills) as kills FROM `player_cache` GROUP BY player_id ORDER BY kills DESC LIMIT 10 OFFSET 30. The above query will offset the results by 30 (i.e. The 3rd ‘page’ of results).
Caching in PHP?
When speed is important you should definitely go for memcached. But in most cases a filecache or sqlite cache serves your needs.
Zend_Cache is a very good Caching library, the fact that it support numerous caching mechanisms through it’s adapter system makes changing caching solutions lateron a breeze, so I would definitely go for Zend_Cache.
To solve this issue, I would:
- Profile the queries to check what is wrong (Index missing, MySQL not properly set).
- Cache the output (Zend_cache, Cache_lite, memecached, etc.) if the database server is really overloaded.
That way, you will understand why your queries are slow.
It really depends on exactly what is causing these queries to be slow, and whether the queries are the same ones again, or if they’re different every time.
Generally speaking, I’d initially focus on why the queries are slow and improving them. The cache used inside the database is efficient because the same cache entries can be used by different queries (assuming they use the same data).
Don’t bother with the MySQL query cache, your database server’s ram is better used increasing the innodb buffer pool (assuming you’re using innodb). The main difficulty with the query cache is that every entry for that table gets thrown out when a single row in the table is modified — even if the results of that particular query had not changed.
The query cache can significantly harm performance if used incorrectly — but the innodb buffer pool is generally only beneficial.
If your data aren’t too big, a cheap and low-risk solution is to buy your db server lots of ram and increase the innodb buffer pool to exceed the size of your data.
Client-side caches will be more scalable (for example, if one per web server) but less effective, and expose stale data to the application (they will probably not be automatically expired when their data become stale).
As with any performance thing, test, test test. Use production-grade hardware, production-like data and workloads.
The most simple way to cache MySQL query results, Repeat the above with the other array that should be stored in a separate file with MD5 of the second query used as the name of second cache file. In the end, you have to decide how long your cache should remain valid. For the same query, there may change records in your mysql table that may make your … Code sampleif( !isset( $array1 ) ) Feedback$array1>
Performance comparison between MySQL queries and static caching
There are many ways to speed up your web site and to lower database load. Those are much better then trying to make manual cache files. Here are some of them:
- Optimize database settings (so many interesting moments!)
- Use memory tables
- Add CPU\RAM to web server
- Use caching servers like nginx or varnish (those can put whole static pages to cache)
- Use special data caching in PHP — like memcached
- Use sockets instead of TCP\IP connection to database
- Use mysql-nd instead of mysql
And here is the answer to your exact question: PHP — Is it good practice to cache MYSQL queries in a txt file?
PHP Best way to cache MySQL results?, You could use MySQL UDF and call a php script on insert/update/delete trigger to invalidate the cache file. By this you will be sure that no old cache file resides in your directory and you may not need to use 60 seconds time. The UDF and trigger can be a way to go – Mohammad Sharaf Ali. Jul 23, …
Что использовать при кешировании запросов MySQL в PHP
Есть необходимость сделать в PHP кеширование выполняемых запросов к MySQL. Но встроенное кеширование в MySQL не подходит по ряду причин. Одна из главных — сброс кеша при любом изменении таблицы — это критично, так как разрабатываемая система многопользовательская. Я уже задумывался, чтобы хранить результаты тяжелых запросов в файлах на сервере и при очередном выполнении запроса (с привязкой к пользователю системы) проверять, если уже такой запрос был, то брать из файла. Но в этом случае придется решать проблему именно отслеживания изменений в таблице.
Можете посоветовать какое-то оптимальное кеширование SQL запросов со стороны PHP? Или может есть ещё какое-то интересное решение?
Заранее благодарен за ответы!
Еще почитайте про redis. Сам его использую для кеширования. Может лучше подойдет вашему проекту, чем мемкеш.
У вас ложная информация по поводу главной причины, которая не дает Вам использовать нормальный вариант, но не это главное. Делайте таблицы-агрегаты. Посмотрите запросы и постройте индексы. Заполняйте их данными после перевода договоров в стабильные статусы. Если у вас есть лишняя оперативка — лучше отдать ее правильно спроектированной БД, чем скармливать бесполезному в этом случае мемкешу, например.
Договора заканчиваются, периоды закрываются, эти данные становятся статикой и хорошо берутся из агрегатов. Вариант с кешем хорош при частых обращениях к одинаковым данным. Ваши пользователи чаще загружают один и тот же договор, или смотрят последовательно разные? Наверняка последнее, а вы забьете оперативку договорами, которые уже не нужны пользователю. Повторюсь — лучше забить эту оперативку индексами.
Но для общего развития изучить все, об чем выше уже рассказали — мегаполезно.
Спасибо за ответ! Да, я и хочу попробовать именно агрегирование финальных данных, которые уже с большой вероятностью не будут меняться, но пока изучаю тему, поэтому все впереди))
А что делать, если сайт является новостным и каждый блок на главной странице делает по несколько запросов? Как лучше в данном случае оптимизировать вывод? Таким образом я пришел к memcache и локальному хранению данных в файлах. Нагрузка упала, но при тестирование через apache инструмент ab, показывает не очень хорошие результаты.
Одна из главных — сброс кеша при любом изменении таблицы — это критично, так как разрабатываемая система многопользовательская. Я уже задумывался, чтобы хранить результаты тяжелых запросов в файлах на сервере и при очередном выполнении запроса (с привязкой к пользователю системы) проверять, если уже такой запрос был, то брать из файла. Но в этом случае придется решать проблему именно отслеживания изменений в таблице.
— Получается немного нелогично. С одной стороны Вас беспокоит сброс кэша при любом изменении таблицы, с другой стороны Вы говорите что на кэш изменения в таблице влияют и их надо отслеживать.
Один из относительно легких вариантов для кэша, это memory таблица в mysql, куда складируются либо все данные которые часто выбираются либо ИД для их выбора из основных таблиц. Плюс по сравнению с 3rd-party решением тут то, что закэшить можно не прогоняя лишние данные через php и сеть, просто insert into select from — в большинстве случаев. Это во-первых. А во-вторых, триггерами при изменениях основной таблицы можно настроить апдейт кэширующей, более гибко чем просто тупой кэш запросов.
Ну и наконец если база относительно небольшая, то innodb + большой размер пула/кэша — тогда вообще все в памяти будет постоянно считай.
Ну да, волнует сброс кеша, так как при определенном количестве пользователей кеширование станет бесполезным, и даже сделает ситуацию хуже, так как эти пользователи будут работать с одной и той же таблицей, кеш будет сбрасываться для всех, и соответственно данные каждый раз все равно будут браться из базы, но при этом ещё будет результат запроса помещаться в кеш, и практически тут же сбрасываться.
Про Memory таблицу спасибо, почитаю, но, если я правильно понял, то в такой таблице фиксированный размер полей, и соответственно, для кеширования результатов, возвращающий разный набор полей необходимы свои таблицы?
Не фиксированный полей, а только поля с фиксированной длиной. Char/int — можно, varchar/longtext — нельзя и т.д…
В остальном — если речь о том, что Вам нужно вытаскивать определённые данные о пользователе, то вопрос в том — какие Вам данные о пользователе нужны? Может проще ввести в таблице пользователей поле типа text и аггрегированные данные (баланс там, очки, карма) хранить там? Вместо огорода с отдельными кэшами? Выборка из таблицы пользователей по ID будет не сильно медленнее чем кэши.
Нет, данные довольно сложные. Разрабатывается система документооборота. И запрос, который выбирает элементарно договора организации, получается сложный. Так как необходимо так же выбрать счета к договору, подсчитать сумму оплат по счетам, и прочие цифры. Договоров может быть весьма много, порядка 100 и больше. И чтобы выполнить такой запрос, БД требуется немаленькое время. Да и данные по объему выходят за рамки стандартных Char и Int. Поэтому хочется сохранять именно результат выборки для конкретного пользователя, чтобы потом просто по запросу его вытаскивать без обращения к БД лишний раз.