php操作redis缓存方法分享
phpredis缓存操作
<?php
/**
*Redis缓存操作
*@authorhxm
*@version1.0
*@since2015.05.04
*/
classRCacheextendsObjectimplementsCacheFace
{
private$redis=null;//redis对象
private$sId=1;//servier服务ID
private$con=null;//链接资源
/**
*初始化Redis
*
*@returnObject
*/
publicfunction__construct()
{
if(!class_exists('Redis'))
{
thrownewQException('PHPextensiondoesnotexist:Redis');
}
$this->redis=newRedis();
}
/**
*链接memcahce服务
*
*@accessprivate
*@paramstring$key关键字
*@paramstring$value缓存内容
*@returnarray
*/
privatefunctionconnect($sid)
{
$file=$this->CacheFile();
require$file;
if(!isset($cache))
{
thrownewQException('缓存配置文件不存在'.$file);
}
$server=$cache[$this->cacheId];
$sid=isset($sid)==0?$this->sId:$sid;//memcache服务选择
if(!$server[$sid])
{
thrownewQException('当前操作的缓存服务器配置文件不存在');
}
$host=$server[$sid]['host'];
$port=$server[$sid]['port'];
try{
$this->redis->connect($host,$port);
}catch(Exception$e){
exit('memecache连接失败,错误信息:'.$e->getMessage());
}
}
/**
*写入缓存
*
*@accessprivate
*@paramstring$key关键字
*@paramstring$value缓存内容
*@returnarray
*/
publicfunctionset($key,$value,$sid,$expire=0)
{
$data=$this->get($key,$sid);//如果已经存在key值
if($data)
{
return$this->redis->getset($key,$value);
}else{
return$this->redis->set($key,$value);
}
}
/**
*读取缓存
*
*@accessprivate
*@paramstring$key关键字
*@paramint$sid选择第几台memcache服务器
*@returnarray
*/
publicfunctionget($key,$sid)
{
$this->connect($sid);
return$this->redis->get($key);
}
/**
*清洗(删除)已经存储的所有的元素
*
*@accessprivate
*@returnarray
*/
publicfunctionflush()
{
$this->connect();
return$this->redis->flushall();
}
/**
*删除缓存
*
*@accessprivate
*@paramstring$key关键字
*@paramint$sid选择第几台memcache服务器
*@returnarray
*/
publicfunctionremove($key,$sid)
{
$this->connect();
return$this->redis->del($key);
}
/**
*析构函数
*最后关闭memcache
*/
publicfunction__destruct()
{
if($this->redis)
{
$this->redis->close();
}
}
}
以上所述就是本文的全部内容了,希望大家能够喜欢。