Data cache is a common performance optimization method in web development. Currently, there are two major file caching or database caching methods. It is not impossible for a database to be cached. It is indeed very good and important. I think traditional databases are mainly considered in terms of business layer and module design, while cache databases are mainly designed at the implementation layer, it is mainly used to cache frequently used multi-table queries. Here, we mainly use file caching and a lot of information on the Internet. Here I have reproduced some principles.
Cache is a typical application mode based on the "space-for-time" policy and an important method to improve system performance. The use of cache can greatly reduce the number of database operations and significantly reduce the system load to improve system performance. Compared with the page cache, The result set is a type of "Raw data" that does not contain the format information. It has a relatively small amount of data and can be formatted, so it is quite flexible. Because PHP is a script language for "Compiling and executing, to some extent, it also provides a convenient way to use the result set cache-by dynamically include the corresponding data definition code segment. If you create a cache on RamDisk, the efficiency can be further improved. The following is a small sample code for your reference.
<?
// load data with cache
function load_data($id,$cache_lifetime) {
// the return data
$data = array();
// make cache filename
$cache_filename = ‘cache_‘.$id.‘.php‘;
// check cache file‘s last modify time
$cache_filetime = filemtime($cache_filename);
if (time() - $cache_filetime <= $cache_lifetime) {
//** the cache is not expire
include($cache_filename);
} else {
//** the cache is expired
// load data from database
// ...
while ($dbo->nextRecord()) {
// $data[] = ...
}
// format the data as a php file
$data_cache = "
while (list($key, $val) = each($data)) {
$data_cache .= "$data[‘$key‘]=array(‘";
$data_cache .= "‘NAME‘=>"".qoute($val[‘NAME‘])."\","
$data_cache .= "‘VALUE‘=>\"".qoute($val[‘VALUE‘])."\""
$data_cache .= ";);\r\n";
}
$data_cache = "?>\r\n";
// save the data to the cache file
if ($fd = fopen($cache_filename,‘w+‘)) {
fputs($fd,$data_cache);
fclose($fd);
}
}
return $data;
}
?>
Applicability:
1. Data is relatively stable, mainly for reading operations.
2. File Operations are faster than database operations.
3. complex data access, large data access, intensive data access, and extremely heavy system database load.
4. Web/DB splitting structure or multiple Web single DB structures.
Unconfirmed problems:
1. Whether the file read/write during concurrent access will cause the locking problem.
2. What is the performance when there are too many data files involved.
Expansion ideas:
1. Generate JavaScript data definition code and call it on the client.
2. I have not thought ......
Hope to discuss it together.