1.根据php版本下载对应的swoole扩展版本进行编译安装,步骤安装官方手册进行安装即可
2.创建一个异步服务器程序Server,只能用于php-cli环境,以thinkphp5为例复制public目录下的入口文件index.php到cli目录cli.php里
4.application目录下创建cli目录控制器TaskServer.php,代码如下:
<?php
namespace app\cli\controller;
/**
* 后台任务
*/
class Taskserver
{
private $serv;
public function start()
{
$this->serv = new \Swoole\Server('0.0.0.0', 9504);
$this->serv->set(array(
'worker_num' => 4,//为CPU核数的1-4倍
'task_worker_num' => 4,
'max_request' => 10000,//最大请求
'daemonize' => 0,//1为守护进程
// 'log_file'=>"/www/log/service/cli/task.log"//日志文件
));
$this->serv->on('Start',function($serv){
echo 'server start!';
});
$this->serv->on('Receive', function($serv, $fd, $from_id, $data) {
echo $data.PHP_EOL;
if (!$data)
{
echo "data error!";
$serv->send($fd,'fail');
}
else
{
$task_id = $serv->task($data);
$serv->send($fd,'ok');
echo "Dispath AsyncTask: id=$task_id".PHP_EOL;
}
});
$this->serv->on('Task', function ($serv, $task_id, $from_id, $data) {
echo "New AsyncTask[id=$task_id,from_id=$from_id]".PHP_EOL;
//这里写入具体执行内容
$serv->finish("$data -> OK".PHP_EOL);
});
$this->serv->on('Finish', function ($serv, $task_id, $data) {
echo "AsyncTask[$task_id] Finish: $data\r\n\r\n";
});
$this->serv->start();
}
5.在linux环境中执行,php安装路径+项目路径
/usr/local/php7/bin/php /www/tp5/cli/cli.php Cli/Taskserver/start
如屏幕输出则创建成功
6.编写api控制器index.php同步client客户端
$client = new \swoole_client(SWOOLE_SOCK_TCP);
if (!$client->connect('0.0.0.0', 9504, 0.5))
{
exit("connect failed. Error: {$client->errCode}\n");
}
$client->send("hello world\n");
echo $client->recv();
$client->close();
执行index.php,在linux屏幕可看到执行结果