用redis减少数据库频繁更新次数
本帖最后由 longniao 于 2012-4-16 15:09 编辑开发过程中,经常遇到各种统计,如网页查看数,每次打开网页,都需要更新数据库,如在view字段加1
此类数据,不需要实时精确,因此可以积累起来批量处理,如1分钟更新一次,简单写了个基于redis类:
<?php
/**
* RedisBatch Class
* @author Longniao <longniao@gmail.com>
* @url http://www.inhai.com/* @version 1.0
*/
class RedisBatch {
public $_Server;
public $_Host;
public $_Port;
public $_Varvar; //数组变量
public $_Vartime; //时间变量
public $_Interval; //时间间隔
public $_Runflag; //执行开关
function __construct()
{
$this->_Server = new Redis();
$this->_Host = '127.0.0.1';
$this->_Port = '6379';
$this->_Varvar = 'batchvar';
$this->_Vartime = 'batchtime';
$this->_Interval = 5;
$this->_Runflag = false;
$this->_Server->connect($this->_Host, $this->_Port);
if($this->_Server->exists($this->_Vartime)){
$lastTime = $this->_Server->get($this->_Vartime);
if(time() - $lastTime > $this->_Interval)
{
$this->_Runflag = true;
$this->refresh();
}
}
else
{
$this->refresh();
}
}
/**
* 添加
*/
public function add($id)
{
return $this->_Server->lpush($this->_Varvar, $id);
}
/**
* 获取
*/
public function get()
{
return $this->_Server->lRange($this->_Varvar, 0, -1);
}
/**
* 清空
*/
public function clear()
{
return $this->_Server->delete($this->_Varvar);
}
/**
* 刷新
*/
public function refresh()
{
return $this->_Server->set($this->_Vartime, time());
}
}
调用方法:
include('redisbatch.php');
$batch = new RedisBatch();
for($i=1; $i<=100; $i++){
$batch->add($i);
}
if($batch->_Runflag){
$get = $batch->get();
var_dump('run');
$batch->clear();
}else{
var_dump('no run');
}
new Redis呢 标题党{:soso_e122:} sdink 发表于 2012-4-13 15:33 static/image/common/back.gif
new Redis呢 标题党
__construct 中就实例化了 :L longniao 发表于 2012-4-16 12:10 static/image/common/back.gif
__construct 中就实例化了
是化了。但是类呢 引入了吗 sdink 发表于 2012-4-16 12:56 static/image/common/back.gif
是化了。但是类呢 引入了吗
只要安装php的redis扩展,就可以直接使用new Redis(),不需要引入 不错学习下
longniao 发表于 2012-4-16 14:51 static/image/common/back.gif
只要安装php的redis扩展,就可以直接使用new Redis(),不需要引入
恩。:handshake 今天看到一个不需要安装phpredis扩展的
https://github.com/joelcox/codeigniter-redis 原来还有这么一个扩展
页:
[1]