主干代码:
利用memcache的前提是急需在服务端先配置好memcahche的条件!确认memcahce能够健康连接之后就能够在程序行使了!
前言
正文实例陈述了PHP使用memcache缓存技术升高响应速度的法子。分享给大家供大家参谋。具体深入分析如下:
<?php
//创建一个memcache对象实例
$memcache = new Memcache;
if(!$memcache->connect("127.0.0.1",11211)){
die('连接失败');
}
if($memcache->set('key1',"xian",MEMCACHE_COMPRESSED,60)){
echo 'sucess!';
}//存值,其中xian字符串,也可以为数组,对象,但不能为资源
$val = $memcache->get('key1');//查询获取值
echo $val;
$memcache->replace('key1','beijing',MEMCACHE_COMPRESSED,60);//修改
$memcache->delete('key1');//删除
?>
<?php
/**
* Memcache缓存操作
* @author hxm
* @version 1.0
* @since 2015.05.04
*/
class MCache extends Object implements CacheFace
{
private $mem = null; //Mem对象
private $sId = 1; //servier服务ID
/**
* 初始化Memcache
*
* @return Object
*/
public function __construct()
{
if ( !class_exists('Memcache') )
{
throw new QException('PHP extension does not exist: Memcache');
}
$this->mem = new Memcache();
}
/**
* 链接memcahce服务
*
* @access private
* @param string $key 关键字
* @param string $value 缓存内容
* @return array
*/
private function connect( $sid )
{
$file = $this->CacheFile();
require $file;
if(! isset($cache) )
{
throw new QException('缓存配置文件不存在'.$file);
}
$server = $cache[$this->cacheId];
$sid = isset($sid) == 0 ? $this->sId : $sid;//memcache服务选择
if ( ! $server[$sid])
{
throw new QException('当前操作的缓存服务器配置文件不存在');
}
$host = $server[$sid]['host'];
$port = $server[$sid]['port'];
try {
$this->mem->connect( $host , $port );
} catch (Exception $e) {
exit('memecache连接失败,错误信息:'. $e->getMessage());
}
}
/**
* 写入缓存
*
* @access private
* @param string $key 关键字
* @param string $value 缓存内容
* @return array
*/
public function set( $key , $value , $sid , $expire = 0)
{
$data = $this->get($key , $sid); //如果已经存在key值
if( $data )
{
return $this->mem->set( $key , $value ,MEMCACHE_COMPRESSED , $expire);
} else {
return $this->mem->add( $key , $value ,MEMCACHE_COMPRESSED , $expire);
}
}
/**
* 读取缓存
*
* @access private
* @param string $key 关键字
* @param int $sid 选择第几台memcache服务器
* @return array
*/
public function get( $key , $sid)
{
$this->connect( $sid );
return $this->mem->get($key);
}
/**
* 清洗(删除)已经存储的所有的元素
*
* @access private
* @return array
*/
public function flush()
{
$this->connect();
return $this->mem->flush();
}
/**
* 删除缓存
*
* @access private
* @param string $key 关键字
* @param int $sid 选择第几台memcache服务器
* @return array
*/
public function remove( $key , $sid)
{
$this->connect();
return $this->mem->delete($key);
}
/**
* 析构函数
* 最后关闭memcache
*/
public function __destruct()
{
/*if(! $this->mem)
{
$this->mem->close();
}*/
}
}
这段时间在专门的工作中又遇到了memcache,我们应该都装有掌握,memcache 是四个高效的布满式的内存对象缓存系统,他得以支撑把php的各个数码(数组,对象,基本数据类型)放在它管理的内部存储器中,本文将给咱们详细介绍有关php操作memcache缓存的根底措施,话相当的少说,来一齐看看详细的牵线吧。
php即便己经做到很好比不慢了,可是一旦大数据量时依然会有个别卡了,这里介绍一下PHP中央银行使memcache缓存本领升高响应速度方法,有要求通晓的意中人可仿效.
上述所述就是本文的全部内容了,希望我们能够欣赏。
1、代码应用
memcache不仅可以够在linux下使用,也能够在windows系统下利用,当然首荐linux系统,至于什么设置memcache,google一下就什么样都出来了.