前言
初级程序员纠结语法bug,高级程序员琢磨工具优势。
本文重点帮PHP程序员,其他程序员请依样画葫芦。
绝招背景
话说,天下武功,唯懒惰不破。
懒惰是推动科技进步的唯一动力。
很多时候,有些人看起来很勤奋,实际效率却异常低下。而高手看起来很懒惰,事情却做得妥妥的。
被动通知,便是高手的一个绝招。
阿里云有“云监控”,本文不讨论该付费服务,为你提供2种白票的手段。
钉钉告警
钉钉机器人,我认为非常好用,强烈推荐。
这也是钉钉比微信更职业化的功能,企业微信也许有,我没去研究。
我封装了一个函数,以下是线上在用的代码:
function dingTalk($post_data)
{
$url = 'https://oapi.dingtalk.com/robot/send?';
$body = array(
"msgtype" => "text",
"text" => array("content" => $post_data['text']),
"at" => array(
"isAtAll" => $post_data['is_at']
)
);
$timeStamp = floor(microtime(true) * 1000);//毫秒时间戳
$stringToSign = $timeStamp . "\n" . $post_data['secret'];//需要签名的字符串
// 进行加密操作 并输出二进制数据
$signature = hash_hmac('sha256', $stringToSign, $post_data['secret'], true);
$query = array(
'access_token' => $post_data['access_token'],
'timestamp' => $timeStamp,
'sign' => base64_encode($signature)
);
$absURL = $url . http_build_query($query);
$handles = curl_init();//初始化CURL句柄
curl_setopt($handles, CURLOPT_RETURNTRANSFER, 1);//设为TRUE把curl_exec()结果转化为字串,而不是直接输出
curl_setopt($handles, CURLOPT_URL, $absURL);//设置请求的URL
curl_setopt($handles, CURLOPT_POST, 1);
curl_setopt($handles, CURLOPT_HTTPHEADER, array('Content-type: application/json;charset=UTF-8')); //设置头信息
curl_setopt($handles, CURLOPT_POSTFIELDS, json_encode($body));
$response = curl_exec($handles);//运行curl
$info = null;
if (!curl_errno($handles)) {
$info = curl_getinfo($handles);
print_r("Took " . $info['total_time'] . " seconds to send a request to " . $info['url'] . " and http code is " . $info['http_code'] . "\n");
} else {
print_r("Curl error: " . curl_error($handles) . "\n");
}
curl_close($handles);
print_r($response . "\n");
}
其中,传入的参数$post_data为:
$post_data = [
'access_token' => 'df088d8f9af3b5f2f7b5f9ed2e146b6f5xxxxxxxxxxx',
'secret' => 'SECffa8b9da6c6290e7e4d8ce5463448f16f9ddb8a9d69xxxxxxxx',
'text' => $text,
'is_at' => true
];
说明:
- access_token和secret:
首先,这个token跟其他的只有2小时有效期的token是不一样的,token和secret的获取全过程不用写一个代码。
它们都在电脑端钉钉(手机端不支持)获取。
获取流程为:点击【群设置】-【智能群助手】(注意不是【群管理】)-【添加机器人】-【自定义】,取名后,在安全设置模块,选择加签,即可得SEC开头的字符串,这就是secret,点击下一步,即可得access_token。
- text即为你要发送的内容,可以是日常数据报告、告警信息、报错信息等。
- is_at,是表示要不要 @ 谁,可以at某个人,也可以at所有人,告警信息一般需要at群里所有人。
这样,就配置好了,随便把上面代码整成一个php文件,机器人就出来了:
邮件提醒
个人觉得,邮件提醒相对钉钉实用性差一些,我已经做实验调试成功了。
时间有限,下次讲。
如果文章对你有用,欢迎关注我,小茂茂喜欢研究拆解程序员经常遇到的困惑。
本文暂时没有评论,来添加一个吧(●'◡'●)