首选要明白redis数据库是怎样的一个数据库
redis是一个key-value存储系统,也就是说知道key就能取得value。(key-value)简单介绍
先简单介绍,后续在增加
下面是同事写的一个redis类文件
<?php
class Hrs2_Db_RedisTable
{
static public $redis = null;
static public $count = 0;
//$configs 注册表config的信息,信息中有redis数据库的host与port。Zend_Registry::get('config')获取注册表config的信息,self::$redis->connect(host, port)方法是连接redis数据库
function __construct() { //类文件的构造方法 __construct()
if(!self::$count){ $configs = Zend_Registry::get('config');
self::$redis = new redis();
self::$redis->connect($configs->databases->redis->host, $configs->databases->redis->port); //connect()连接数据库
}
self::$count++;
}
function __destruct(){ //类文件的析构方法 __destruct() 对象销毁时调用的方法
self::$count--;
if(!self::$count){
self::$redis->close(); //关闭redis数据库的连接 self::$redis->close();
}
}
function __call($method, $args){
return call_user_func_array(array(&self::$redis,$method),$args);
}
//getKey()方法返回redis数据库名与数据库表名和当前表的key值
protected function getKey($key){
$table = str_replace('_', '.', $this->_name);
$dbname = str_replace('_', '.', $this->_dbaName);
return "{$dbname}:{$table}:{$key}";
}
}
?>
根据key值直接读取value值
调用get($key)方法就能直接得到value的值。
获取
$key = $this->getKey($key); //$key包含了dbname:table:key
$value = $this->get($key); //获取dbname:table:key对应的value
保存
$key = $this->getKey($key); //dbname:table:key
$data = serialize($data); //序列化数据
return $this->setex($key, 86400*30, $data); //1个月后超期 //setex($key, 86400*30, $data); 保存数据到redis数据库