当前位置: 移动技术网 > IT编程>开发语言>PHP > PHP Memcached + APC + 文件缓存封装实现代码

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

2019年05月01日  | 移动技术网IT编程  | 我要评论
使用方法:
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
复制代码 代码如下:

<?php

abstract class cache_abstract {
abstract function fetch($key);
abstract function store($key, $data, $ttl);
abstract function delete($key);
}

class cache_apc extends cache_abstract {

function fetch($key) {
return apc_fetch($key);
}

function store($key, $data, $ttl) {
return apc_store($key, $data, $ttl);
}

function delete($key) {
return apc_delete($key);
}

}

class cache_memcache extends cache_abstract {
public $connection;

function __construct() {
$this->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);
}

}
?>

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网