本文主要按照给快到期的微信用户发送模板消息,提醒续费来讲解,主要和大家分享php之swoole多进程发送微信模板消息,希望能帮助到大家。
首先拿到快到期的用户, 每天大概800-2000不等,感觉压力不是很大,直接foreach 数组 然后发送,经常出现请求超时 也就是502的问题,紧接着运营同事提出要针对一大批用户 推模板消息,年前搞一波促销,量每天在1万左右,于是楞冲冲的 直接做了个上传功能,给运营人员直接上传发送,然后用是无限的502bad way.
此时 ,感觉模板消息数量上去了,需要优化,于是采用另外一种方案,redis队列+守护进程,将上传的数据跟发送的解耦, 守护进程检测redis队列中是否存在需要发送的数据,如果存在就开始 一条条往外取,然后发送.此方案感觉是运营人员不用管结果,肯定能发送成功,但是时间比较长,量大了 很长时间才发完, 那么就出现了另外一个问题,发出去的时间不用,想在用户打开微信的最高峰时间段发送给用户.好继续优化!
此时改用php+swoole 来进行多进程异步处理,既然一个进程慢,那咱就多开几个,于是16个进程一起异步发送,1万模板消息 10分钟之内发完,基本改造完成.
首先启动server.php
客户端
class client
{
public function send($msg){
$client = new swoole_client(swoole_sock_tcp);
//连接到服务器
if (!$client->connect('127.0.0.1', 9501, 0.5))
{
$this->write("connect failed.");
}
//向服务器发送数据
if (!$client->send($msg))
{
$this->write("send ".$msg." failed.");
}
//关闭连接
$client->close();
}
private function write($str){
$path = "/sys.log";
$str = "[".date("y-m-d h:i:s")."]".$str;
$str .= php_eol;
file_put_contents($path,$str,file_append);
}
}
服务端
<?php
$serv = new swoole_server("127.0.0.1", 9501);
//设置异步任务的工作进程数量
$serv->set(array('task_worker_num' =>16));
//监听数据接收事件
$serv->on('receive', function($serv, $fd, $from_id, $data) {
//投递异步任务
$task_id = $serv->task($data);//非阻塞
echo "同步代码执行完成\n";
});
//处理异步任务
$serv->on('task', function ($serv, $task_id, $from_id, $data) {
handlefun($data);
//返回任务执行的结果
$serv->finish("finish");
});
//处理异步任务的结果
$serv->on('finish', function ($serv, $task_id, $data) {
echo "异步任务执行完成";
});
$serv->start();
function handlefun($data){
$data=json_decode($data,true);
foreach ($data as $key => $value) {
echo json_encode($value);
$url="xxxx";//调用发送模板消息接口,服务端没办法直接获取微信的接口的一些数据,此处做了一些加密
$posturl = $url;
$curlpost = $value;
$ch = curl_init(); //初始化curl
curl_setopt($ch, curlopt_url, $posturl); //抓取指定网页
curl_setopt($ch, curlopt_header, 0); //设置header
curl_setopt($ch, curlopt_returntransfer, 1); //要求结果为字符串且输出到屏幕上
curl_setopt($ch, curlopt_post, 1); //post提交方式
curl_setopt($ch, curlopt_postfields, $curlpost);
$data = curl_exec($ch); //运行curl
curl_close($ch);
}
}
调用client.php
<?php
include dirname(__file__).'/client.php';
$params=""//接口数据
$msg = json_encode($params);
$client = new client();$client->send($msg);echo "[".date("y-m-d h:i:s")."]执行完成".php_eol;
相关推荐:
phpstorm如何增加swoole自动提示
thinkphp5和swoole异步邮件群发实现方法
swoole 实现微信扫码登录功能
以上就是php之swoole多进程发送微信模板消息的详细内容。