项目中,有遇到一个问题,发送三百万条数据,如果用普通的阻塞发送,一天完成任务(白天),恐怕服务器都会罢工。

用swoole 测试了下,把task 开到1000个,也就是一秒钟,可以同时发1000条数据。swoole 最大开启task 数量为4000,这个根据自身的服务器的性能来决定,开多少个合适。

微信发送百万模板消息swoole 定时任务不能异步task问题_服务器

这个时候就遇到了个问题,如果用swoole 的异步定时任务。则会报错,是因为,官方介绍说明了,异步不能再异步。也就是task里面不能有task任务。

于是想到了,把swoole 当作http服务器,定时任务触发的是http请求,再触发任务,在任务中分配task

代码如下:

<?php

class Http{
public $http=null;
public function __construct()
{
$this->http = new swoole_http_server('0.0.0.0',9502);
$this->http->on('start',[$this,'onstart']);
$this->http->on('request',[$this,'onrequest']);
$this->http->on('task',[$this,'ontask']);
$this->http->on('finish',[$this,'onfinish']);
$this->http->set([
'task_worker_num'=>1000,
]);
$this->http->start();
}
public function onstart($server){
$this->http->reload();
swoole_timer_tick(10000,function (){
$this->getnet();
});
}
public function ontask(){
$data = file_get_contents('http://www.baidu.com/');
echo '成功';
}
public function onfinish(){

}
public function onrequest($request,$response){
//投递任务的地方:

for($i=0;$i<300;$i++){
$this->http->task('kkkk');
}
}
public function getnet(){
Swoole\Async::dnsLookup("0.0.0.0", function ($domainName, $ip) {
$cli = new swoole_http_client($ip, 9502);
global $http;
$cli->get('index', function ($cli) {

});
});
}
}
new Http;



?>