Swoole实时任务异步调用Demo

server.php

<?php  
class Server  
{  
    private $serv;  
    private $logFilePath = "/data/wwwroot/houtai/Log/taskqueueu.log";

    public function __construct()  
    {  
        $this->serv = new swoole_server("0.0.0.0", 9515);  
        $this->serv->set(array(  
            'worker_num' => 1, //一般设置为服务器CPU数的1-4倍  
            'daemonize' => 0, //1以守护进程执行,0 ssh的命令行模式
            'max_request' => 10000,  
            'dispatch_mode' => 2,  
            'task_worker_num' => 8, //task进程的数量,数值越小消耗的时间越长
//            "task_ipc_mode " => 3, //使用消息队列通信,并设置为争抢模式
            "log_file" => $this->logFilePath ,//日志存放目录
        ));  
        $this->serv->on('Receive', array($this, 'onReceive'));  
        // bind callback  
        $this->serv->on('Task', array($this, 'onTask'));  
        $this->serv->on('Finish', array($this, 'onFinish'));  
        $this->serv->start();  
    }  
  
    public function onReceive(swoole_server $serv, $fd, $from_id, $data)  
    {  
        //echo "Get Message From Client {$fd}:{$data}\n";  
        $task_id = $serv->task($data);  
		$serv->send($fd,$task_id." received "."\n");
    }  
  
    public function onTask($serv, $task_id, $from_id, $data)  
    {
          sleep(10);
          //在这里进行脚本执行处理操作
          echo $data."\n";
		  $f = fopen($this->logFilePath,"a+");
		  $current = date("Ymd H:i:s");
		  fwrite($f,$current.$data."\n");
		  fclose($f);
		  //$serv->finish($task_id." ok "."\n");
		  return $task_id;
    }  
  
    public function onFinish($serv, $task_id, $data)  
    {  
        //任务完成自动调用
        $current = date("Ymd H:i:s");
		echo $current." ".$task_id." finish"."\n";
    }  
	
}  
  
$server = new Server();  

  client.php

 

<?php  
  
class Client  
{  
    public $client;  
  
    public function __construct()  
    {  
        $this->client = new swoole_client(SWOOLE_SOCK_TCP);  
    }  
  
    public function connect()  
    {  
        if (!$this->client->connect("127.0.0.1", 9515, 1)) {  
            throw new Exception(sprintf('Swoole Error: %s', $this->client->errCode));  
        }  
    }  
  //传输数据
    public function send($data)  
    {  
        if ($this->client->isConnected()) {  
          
            return $this->client->send($data);  
        } else {  
            throw new Exception('Swoole Server does not connected.');  
        }  
    }

    	
  
    public function close()  
    {  
        $this->client->close();  
    }  
}  
  
$data = array(  
    "params"=>"参数信息"
);  
$client = new Client();  
$client->connect();  
for ($i = 0; $i<10;$i++){
	if ($client->send(json_encode($data))) {  
		echo 'send success'."\n";
	} else {  
		echo 'send fail';
	}  
	$response = $client->client->recv();
	if ($response) {  
		echo $response."\n";  
	}
}

$client->close();

  

运行方法:

先命令行启动php server.php

后命令行启动php client.php

然后观察客户端的输出+日志的内容。

服务端的task_worker_num设置的数值越小,花费的时间越长。

posted @ 2020-05-23 14:08  tochenwei  阅读(331)  评论(0编辑  收藏  举报