How to cache PHP page which has mysql query. Any example will be great and helpful.
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
I am using phpFastCache ( for shared hosting, if you don't want to touch php.ini and root to setup memcached). Check out the Example Menu. They have full detail example, and very easy.
First you set with phpFastCache::set and then get with phpFastCache::get - DONE!
Example: Reduce Database Calls
Your website have 10,000 visitors who are online, and your dynamic page have to send 10,000 same queries to database on every page load. With phpFastCache, your page only send 1 query to DB, and use the cache to serve 9,999 other visitors.
memcache your html out and then do something like this:
My preference is to use a caching reverse proxy, like Varnish.
As far as a pure PHP solution, you could have some code at the end of your script that caches the final output, and code at the beginning that checks to see if the page is cached. If the page was found in cache, send it and exit rather than running the queries again.
Obviously this needs lots of customization for your setup, including cache expiration, a
$cache_key
that meets your needs, and error detection so bad pages aren't cached.The important thing, often overlooked when there is discussion about caching, is process synchronization to avoid thread race (see: https://en.wikipedia.org/wiki/Race_condition).
Typical caching scenario in PHP without synchronization looks like this: if you don't have resource in the cache, or resource is expired, it must be created and put into cache. First thread/process that happens to encounter such condition is trying to create resource, and during that time, other threads will also create the resource, which leads to thread race, cache slamming and performance downspike.
Problem is magnified by number of concurrent threads and workload created by resource creation task. On busy systems it may lead to serious problems.
There is very few caching systems for PHP that takes it into consideration synchronization.
One of them is php-no-slam-cache: https://github.com/tztztztz/php-no-slam-cache