需求:redis队列在定时的写入数据库。如果检测到redis队列的php脚本停止了,就重新启动该php脚本。
实现如下:
ps -ef | grep 01FirstScript.sh | grep -v grep,此命令可以查看到该sh脚本或者php脚本是否在运行
然后编写定时脚本监控程序
因为我的脚本是在本地写的,格式肯定有问题,【注意传到linux后,修改sh格式】
用vi或者vim打开文件,然后用命令 :set fileformat=unix,保存退出就可以了。
crontab.sh
#!/bin/bash
#进程监控脚本
#功能需求: 监控程序是否运行,如果程序没有运行,那么启动程序。
while [ true ]
do
shpro="/www/xiaoqi/queue/process.sh"
PIDS=$(ps -ef | grep /www/xiaoqi/queue/index.php |grep -v grep)
if [ "$PIDS" == "" ]
#过滤出目标进程信息,如果pro为空串说明目标进程未运行
#反向过滤掉grep进程 和 本进程信息, 因为这两个进程信息中包含目标进程的名字
then
echo "程序未启动,重新启动程序"
sh $shpro #重新启动指定程序
else
echo "程序正在运行..."
fi
sleep 1
done
测试:
看程序执行
正常。
process.sh
#!/bin/bash
#file_name : process.sh
#author : queue
php /www/xiaoqi/queue/index.php
贴一下我的redis队列代码
<?php
include_once "redis.php";
include_once "mysql.php";
$db = new PDO('mysql:host=localhost;dbname=datahk', 'aaaaa', 'bbbb');
$rs = $db->query('select * from cmf_user_browse where id=21');
$a = $rs->fetch(PDO::FETCH_ASSOC);
var_dump($a);exit;
getRpop();
function getRpop(){
$redis = getRedis();
$mysql = getMysql();
while (1) {
//list类型出队操作,无限重复执行
if($redis->exists('userAgent_data')){
$data = $redis->rPop('userAgent_data');
if(isset($data) && !empty($data)){
$data = json_decode($data,true);
if(!isset($data['type'])){ //添加操作
$mysql->insert('cmf_user_browse',$data);
}else{ //修改操作
$userBrowse = $mysql->query("select `id`,`viewing_hours` from cmf_user_browse where cookie_val = ".$data['cookie_val']. " and parameter = '".$data['parameter']."' and time = ".$data['times'],'Row');
if($userBrowse){
$update_data = array(
'viewing_hours' => (int)$userBrowse['viewing_hours'] +60
);
$mysql->update('cmf_user_browse',$update_data,'id = '.$userBrowse['id']);
}
}
}
}else{
continue;
}
}
}
//获取mysql实例
function getMysql(){
$config = include_once "config.php";
$config = $config['mysql'];
$mysql = DB::getInstance($config['host'],$config['user'],$config['password'],$config['dbname'],$config['charset']);
return $mysql;
}
//获取redis实例
function getRedis(){
$redis = redisDb::getInstance();
return $redis;
}