2022-11-02

用redis保存行数判断文本无新增,并企业微信通知

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$key = 'max_hang';

//$file_path = ; //文件路径
$line = 0; //初始化行数
//打开文件

$fp = fopen("../../phpServer/logs/php_error.log", 'r') or die("open file failure!");

if ($fp) {
//获取文件的一行内容,注意:需要php5才支持该函数;
    while (stream_get_line($fp, 8192, "\n")) {
        $line++;
    }
    fclose($fp);//关闭文件
}
$val = $redis->get($key);

$notice = array(
    'msgtype' => 'text',
);
//输出行数;
if ($line > $val) {
    file_put_contents("_baidu_1027.txt", "脚本再运行中…… Redis: $val, 当前行: $line \n", FILE_APPEND);
    //echo "脚本再运行中…… Redis: $val, 当前行: $line " . PHP_EOL;
    $notice['text']['content'] = '百度搜索正在运行中...';
    $notice['text']['mentioned_list'] = ['qishang.wu'];
    doCurlPostRequest('https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=', $notice);
} else {
    $notice['text']['content'] = '百度搜索已结束.';
    doCurlPostRequest('https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=', $notice);
    file_put_contents("_baidu_1027.txt", "无新增日志,脚本已跑结束, Redis: $val, 当前行: $line \n", FILE_APPEND);
    //echo "无新增日志,脚本已跑结束, Redis: $val, 当前行: $line " . PHP_EOL;
}

if ($val) {
    $hang = $val;
} else {
    $hang = $line;
}
$redis->set($key, $line);


function doCurlPostRequest($url = '', $data = array())
{
    $data_string = json_encode($data,JSON_UNESCAPED_UNICODE);
    // $data_string = $data;
    $curl_con = curl_init();
    curl_setopt($curl_con, CURLOPT_URL,$url);
    curl_setopt($curl_con, CURLOPT_HEADER, false);
    curl_setopt($curl_con, CURLOPT_POST, true);
    curl_setopt($curl_con, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl_con, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($curl_con, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string))
    );
    curl_setopt($curl_con, CURLOPT_POSTFIELDS, $data_string);
    $res = curl_exec($curl_con);
    $status = curl_getinfo($curl_con);
    curl_close($curl_con);

    if (isset($status['http_code']) && $status['http_code'] == 200) {
        return $res;
    } else {
        return FALSE;
    }
}

发表回复

Your email address will not be published. Required fields are marked *