PHP Memcached + APC + 文件缓存封装实现代码

高洛峰
发布: 2016-12-30 13:34:44
原创
1132 人浏览过

使用方法:
Memcached

$cache = new Cache_MemCache(); $cache->addServer('www1'); $cache->addServer('www2',11211,20); // this server has double the memory, and gets double the weight $cache->addServer('www3',11211); // Store some data in the cache for 10 minutes $cache->store('my_key','foobar',600); // Get it out of the cache again echo($cache->fetch('my_key'));
登录后复制

文件缓存

$cache = new Cache_File(); $key = 'getUsers:selectAll'; // check if the data is not in the cache already if (!$data = $cache->fetch($key)) { // assuming there is a database connection $result = mysql_query("SELECT * FROM users"); $data = array(); // fetching all the data and putting it in an array while($row = mysql_fetch_assoc($result)) { $data[] = $row; } // Storing the data in the cache for 10 minutes $cache->store($key,$data,600); }
登录后复制

下载: class_cache3.php

connection = new MemCache; } function store($key, $data, $ttl) { return $this->connection->set($key, $data, 0, $ttl); } function fetch($key) { return $this->connection->get($key); } function delete($key) { return $this->connection->delete($key); } function addServer($host, $port = 11211, $weight = 10) { $this->connection->addServer($host, $port, true, $weight); } } class Cache_File extends Cache_Abstract { function store($key, $data, $ttl) { $h = fopen($this->getFileName($key), 'a+'); if (!$h) throw new Exception('Could not write to cache'); flock($h, LOCK_EX); fseek($h, 0); ftruncate($h, 0); $data = serialize(array(time() + $ttl, $data)); if (fwrite($h, $data) === false) { throw new Exception('Could not write to cache'); } fclose($h); } function fetch($key) { $filename = $this->getFileName($key); if (!file_exists($filename)) return false; $h = fopen($filename, 'r'); if (!$h) return false; flock($h, LOCK_SH); $data = file_get_contents($filename); fclose($h); $data = @ unserialize($data); if (!$data) { unlink($filename); return false; } if (time() > $data[0]) { unlink($filename); return false; } return $data[1]; } function delete($key) { $filename = $this->getFileName($key); if (file_exists($filename)) { return unlink($filename); } else { return false; } } private function getFileName($key) { return '/tmp/s_cache' . md5($key); } } ?>
登录后复制

更多PHP Memcached + APC + 文件缓存封装实现代码相关文章请关注PHP中文网!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门推荐
    最新下载
    更多>
    网站特效
    网站源码
    网站素材
    前端模板
    关于我们 免责声明 Sitemap
    PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!