|
本帖最后由 longniao 于 2012-4-16 15:09 编辑
开发过程中,经常遇到各种统计,如网页查看数,每次打开网页,都需要更新数据库,如在view字段加1
此类数据,不需要实时精确,因此可以积累起来批量处理,如1分钟更新一次,简单写了个基于redis类:
PHP复制代码 <?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());
}
}
复制代码
调用方法:
PHP复制代码
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');
}
复制代码
|
评分
-
查看全部评分
|