利用php +swoole如何实现异步任务队列

零到壹度
发布: 2023-03-23 11:28:01
原创
3428 人浏览过

本篇文章给大家分享的内容是php +swoole如何实现异步任务队列  ,有着一定的参考价值,有需要的朋友可以参考一下

假如要发100封邮件,for循环100遍,用户直接揭竿而起,什么破网站!
但实际上,我们很可能有超过1万的邮件。怎么处理这个延迟的问题?
答案就是用异步。把“发邮件”这个操作封装,然后后台异步地执行1万遍。这样的话,用户提交网页后,他所等待的时间只是“把发邮件任务请求推送进队列里”的时间。而我们的后台服务将在用户看不见的地方跑。
在实现“异步队列”这点上,有人采用MySQL表或者redis来存放待发送的邮件,然后,每分钟定时读取待发送列表,然后处理。这便是定时异步任务队列。但当前提交的任务要一分钟后才能执行,在某些实时性要求高的应用场景里还是不快,比如发送短信的场景,只要一提交任务,便要马上执行,用户不需要等待返回结果。

以下将探讨用php扩展swoole实现实时异步任务队列发送短信的方案。

服务端

第一步:创建tcp服务器

第二步:设置服务器的相关属性

第三步:设置服务端的相关回调函数处理任务

具体代码如下:tcp_server.php

<?php
class Server{
  private $serv;
  public function __construct(){

    $this->serv = new swoole_server("0.0.0.0",9501);
    $this->serv->set(
      array(  
            &#39;worker_num&#39; => 1,                //一般设置为服务器CPU数的1-4倍  
            &#39;daemonize&#39; => 1,                 //以守护进程执行  
            &#39;max_request&#39; => 10000,  
            &#39;dispatch_mode&#39; => 2,  
            &#39;task_worker_num&#39; => 8,           //task进程的数量  
            "task_ipc_mode " => 3,            //使用消息队列通信,并设置为争抢模式  
            "log_file" => "log/taskqueueu.log",
        )
    );
    $this->serv->on(&#39;Receive&#39;,array($this,&#39;onReceive&#39;));
    $this->serv->on(&#39;Task&#39;,array($this,&#39;onTask&#39;));
    $this->serv->on(&#39;Finish&#39;,array($this,&#39;onFinish&#39;));   
    $this->serv->start();

  }
  public function onReceive(swoole_server $serv, $fd, $from_id, $data){
    $serv->task($data);
  }
  public function onTask($serv, $task_id, $from_id, $data){
    $data = json_decode($data,true);
    if(!empty($data)){
      return $this->sendsms($data[&#39;mobile&#39;],$data[&#39;message&#39;]);   
    }
  }
  public function onFinish($serv, $task_id, $data){
      echo "Task {$task_id} finish\n";
  }
  public function sendsms($mobile,$text)
	{
		$timestamp = date("Y-m-d H-i-s");
		$pid = "888888888";
		$send_sign = md5($pid.$timestamp."abcdefghijklmnopqrstuvwxyz");
		$post_data = array();  
		$post_data[&#39;partner_id&#39;] = $pid;  
		$post_data[&#39;timestamp&#39;] =$timestamp;  
		$post_data[&#39;mobile&#39;] = $mobile;  
		$post_data[&#39;message&#39;] = $text;  
		$post_data[&#39;sign&#39;] = $send_sign;  
		$url=&#39;http://182.92.149.100/sendsms&#39;;  
		$o="";  
		foreach ($post_data as $k=>$v)  
		{  
			$o.= "$k=".urlencode($v)."&";  
		}  
		$post_data=substr($o,0,-1);  
		$ch = curl_init();  
		curl_setopt($ch, CURLOPT_POST, 1);  
		curl_setopt($ch, CURLOPT_HEADER, 0);  
		curl_setopt($ch, CURLOPT_URL,$url);  

		//为了支持cookie  
		//curl_setopt($ch, CURLOPT_COOKIEJAR, &#39;cookie.txt&#39;);  
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);  
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$result = curl_exec($ch);  
		if(strpos($result,"success")!==false)
		{
			$outstr=1;
		}
		else
		{
			$outstr=502;
		}
		return $outstr;
	
	}
}
$server = new Server();
?>
登录后复制

客户端

启动后端服务后,客户端首先创建tcp客户端服务器,然后连接tcp后端服务器,并向后端tcp服务器发送数据,具体代码如下:client.php

<?php
class Client{
  public $client;
  public function __construct(){
    $this->client= new swoole_client(SWOOLE_SOCK_TCP);//默认同步tcp客户端,添加参数SWOOLE_SOCK_ASYNC为异步
  }
  public function connect(){
    if(!$this->client->connect(&#39;127.0.0.1&#39;,9501,1)){
      throw new Exception(sprintf(&#39;Swoole Error: %s&#39;, $this->client->errCode));
    }
  }
  public function send($data){
    if($this->client->isConnected()){
      $data = json_encode($data);
      //print $data;  
      if($this->client->send($data)){
         return 1;    
      }else{
        throw new Exception(sprintf(&#39;Swoole Error: %s&#39;, $this->client->errCode));
      }
    }else{
      throw new Exception(&#39;Swoole Server does not connected.&#39;);  
    }

  }
  public function close(){
    $this->client->close();
  }
}
$client= new Client();
$client->connect();
$data=array(
  &#39;mobile&#39;=>&#39;18511487955&#39;,
  &#39;message&#39;=>&#39;you mobile 18511487955&#39;
);
if($client->send($data)){
  echo &#39;succ&#39;;
}else{
  echo &#39;fail&#39;;
}
?>
登录后复制

相关推荐:

异步任务队列的两种处理方法 

PHP使用swoole来实现实时异步任务队列

spring boot-使用redis的Keyspace Notifications实现定时任务队列

以上是利用php +swoole如何实现异步任务队列 的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!