本篇文章主要介绍了" redis队列缓存 + mysql 批量入库 + php离线整合",主要涉及到队列,Exception,crontab,索引,插入数据方面的内容,对于PHPjrs看球网直播吧_低调看直播体育app软件下载_低调看体育直播感兴趣的同学可以参考一下:
需求背景:有个调用统计日志存储和统计需求,需要存储到mysql中;瓶颈在于直接入库并发太高,直接会把mysql干垮。问题分析问题一:要求日志最好入库;但是,直接...
队列中的脚本,拼接sql,批量入库。
* @update 2015-11-07 添加失败消息队列回滚机制
*
* @Author:cuihuan
* 2015-11-06
* */
// init redis
$redis_xx = new Redis();
$redis_xx->connect('ip', port);
$redis_xx->auth("password");
// 获取现有消息队列的长度
$count = 0;
$max = $redis_xx->lLen("call_log");
// 获取消息队列的内容,拼接sql
$insert_sql = "insert into fb_call_log (`interface_name`, `createtime`) values ";
// 回滚数组
$roll_back_arr = array();
while ($count < $max) {
$log_info = $redis_cq01->lPop("call_log");
$roll_back_arr = $log_info;
if ($log_info == 'nil' || !isset($log_info)) {
$insert_sql .= ";";
break;
}
// 切割出时间和info
$log_info_arr = explode("%",$log_info);
$insert_sql .= " ('".$log_info_arr[0]."','".$log_info_arr[1]."'),";
$count++;
}
// 判定存在数据,批量入库
if ($count != 0) {
$link_2004 = mysql_connect('ip:port', 'user', 'password');
if (!$link_2004) {
die("Could not connect:" . mysql_error());
}
$crowd_db = mysql_select_db('fb_log', $link_2004);
$insert_sql = rtrim($insert_sql,",").";";
$res = mysql_query($insert_sql);
// 输出入库log和入库结果;
echo date("Y-m-d H:i:s")."insert ".$count." log info result:";
echo json_encode($res);
echo "
\n";
// 数据库插入失败回滚
if(!$res){
foreach($roll_back_arr as $k){
$redis_xx->rPush("call_log", $k);
}
}
// 释放连接
mysql_free_result($res);
mysql_close($link_2004);
}
// 释放redis
$redis_cq01->close();
?>
四:离线天级统计和清理数据脚本
?php
/**
* static log :每天离线统计代码日志和删除五天前的日志
*
* @Author:cuihuan@baidu.com
* 2015-11-06
* */
// 离线统计
$link_2004 = mysql_connect('ip:port', 'user', 'pwd');
if (!$link_2004) {
die("Could not connect:" . mysql_error());
}
$crowd_db = mysql_select_db('fb_log', $link_2004);
// 统计昨天的数据
$day_time = date("Y-m-d", time() - 60 * 60 * 24 * 1);
$static_sql = "get sql";
$res = mysql_query($static_sql, $link_2004);
// 获取结果入库略
// 清理15天之前的数据
$before_15_day = date("Y-m-d", time() - 60 * 60 * 24 * 15);
$delete_sql = "delete from xxx where createtime < '" . $before_15_day . "'";
try {
$res = mysql_query($delete_sql);
}catch(Exception $e){
echo json_encode($e)."\n";
echo "delete result:".json_encode($res)."\n";
}
mysql_close($link_2004);
?>
五:代码部署
主要是部署,批量入库脚本的调用和天级统计脚本,crontab例行运行。