您好,登录后才能下订单哦!
小编给大家分享一下Swoole如何使用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
我们使用PHP开发WEB应用基本都是使用传统的LAMP/LNMP模式来提供HTTP服务,这种模式一般是同步且堵塞的,若我们想使用PHP开发一些高级的特性(例如:异步,非堵塞,网络服务器等),那么Swoole无疑是最佳的选择,那什么是Swoole呢?
PHP的异步、并行、高性能网络通信引擎,使用纯C语言编写,提供了 PHP语言的异步多线程服务器, 异步TCP/UDP网络客户端, 异步MySQL, 异步Redis, 数据库连接池, AsyncTask, 消息队列, 毫秒定时器, 异步文件读写, 异步DNS查询。 Swoole内置了 Http/WebSocket服务器端/ 客户端、 Http2.0服务器端/ 客户端。
简单的来说,Swoole是一个PHP扩展,实现了网络层的很多功能,应用场景非常广,下面列举几个例子简单介绍一下Swoole的应用。
按照官方文档进行安装:Swoole官网,安装完后使用命令:
php -m
查看是否安装成功。注意:Swoole从2.0版本开始支持了内置协程,需使用PHP7。
使用Swoole提供TCP服务,异步任务发送邮件。
邮件功能:
PHPMailer
PHP主代码:
<?php $object = new MailServer(); $setting = [ 'log_file' => 'swoole.log', 'worker_num' => 4, // 4个工作进程 'task_worker_num' => 10, // 10个任务进程 ]; $server = new swoole_server("127.0.0.1", 9501); $server->set($setting); $server->on('WorkerStart', array($object, 'onWorkerStart')); $server->on('Connect', array($object, 'onConnect')); $server->on('Receive', array($object, 'onReceive')); $server->on('Close', array($object, 'onClose')); $server->on('Task', array($object, 'onTask')); $server->on('Finish', array($object, 'onFinish')); $server->start(); class MailServer { /** @var Mail */ private $handle; public function __construct() { require 'Mail.php'; // PHPMailer邮件服务类 } public function onWorkerStart($server, $workerId) { $mailConfig = require 'MailConfig.php'; // 发件人信息,重启时会重新加载配置文件 $this->handle = new Mail($mailConfig); } public function onConnect($server, $fd, $reactorId) { } public function onReceive($server, $fd, $reactorId, $data) { $return = []; $dataArr = json_decode($data, true); if (empty($dataArr) || empty($dataArr['address']) || empty($dataArr['subject']) || empty($dataArr['body'])) { $return['code'] = -1; $return['msg'] = '参数不能为空'; } else { // 参数校验成功 $server->task($data); // 投递一个任务 $return['code'] = 0; $return['msg'] = '投递任务成功'; } $server->send($fd, json_encode($return)); } public function onTask($server, $taskId, $workerId, $data) { $data = json_decode($data, true); $this->handle->send($data['address'], $data['subject'], $data['body']); // 发送邮件 } public function onFinish($server, $task_id, $data) { } public function onClose($server, $fd, $reactorId) { } }
发件人信息配置:
<?php // 邮件发送人信息配置 return [ 'host' => 'smtp.qq.com', 'port' => '465', 'fromName' => 'Mr.litt', 'username' => '137057181@qq.com', 'password' => '', ];
PHPMailer邮件服务类:
<?php require 'vendor/phpmailer/phpmailer/src/Exception.php'; require 'vendor/phpmailer/phpmailer/src/PHPMailer.php'; require 'vendor/phpmailer/phpmailer/src/SMTP.php'; use PHPMailer\PHPMailer\PHPMailer; class Mail { private $host; private $port; private $fromName; private $username; private $password; public function __construct($config) { !empty($config['host']) && $this->host = $config['host']; !empty($config['port']) && $this->port = $config['port']; !empty($config['fromName']) && $this->fromName = $config['fromName']; !empty($config['username']) && $this->username = $config['username']; !empty($config['password']) && $this->password = $config['password']; if (empty($this->host) || empty($this->port) || empty($this->fromName) || empty($this->username) || empty($this->password)) { throw new Exception('发件人信息错误'); } } public function send($address, $subject, $body) { if (empty($address) || empty($subject) || empty($body)) { throw new Exception('收件人信息错误'); } // 实例化PHPMailer核心类 $mail = new PHPMailer(); // 是否启用smtp的debug进行调试 开发环境建议开启 生产环境注释掉即可 默认关闭debug调试模式 $mail->SMTPDebug = 0; // 使用smtp鉴权方式发送邮件 $mail->isSMTP(); // smtp需要鉴权 这个必须是true $mail->SMTPAuth = true; // 链接邮箱的服务器地址 $mail->Host = $this->host; // 设置使用ssl加密方式登录鉴权 $mail->SMTPSecure = 'ssl'; // 设置ssl连接smtp服务器的远程服务器端口号 $mail->Port = $this->port; // 设置发送的邮件的编码 $mail->CharSet = 'UTF-8'; // 设置发件人昵称 显示在收件人邮件的发件人邮箱地址前的发件人姓名 $mail->FromName = $this->fromName; // smtp登录的账号 QQ邮箱即可 $mail->Username = $this->username; // smtp登录的密码 使用生成的授权码 $mail->Password = $this->password; // 设置发件人邮箱地址 同登录账号 $mail->From = $this->username; // 邮件正文是否为html编码 注意此处是一个方法 $mail->isHTML(true); // 设置收件人邮箱地址 $mail->addAddress($address); // 添加多个收件人 则多次调用方法即可 //$mail->addAddress('87654321@163.com'); // 添加该邮件的主题 $mail->Subject = $subject; // 添加邮件正文 $mail->Body = $body; // 为该邮件添加附件 //$mail->addAttachment('./example.pdf'); // 发送邮件 返回状态 $status = $mail->send(); return $status; } }
注意事项:
修改发件人信息后,只需重启task_worker就生效,命令 kill -USER1 主进程PID。
TCP客户端可使用swoole_client类来模拟。
短信、推送等异步任务同样适用于此场景。
使用Swoole提供WebSocket服务,使用Redis保存房间人员信息。
PHP主代码:
<?php $object = new ChatServer(); $setting = [ 'log_file' => 'swoole_ws.log', 'worker_num' => 4, // 4个工作进程 ]; $ws = new swoole_websocket_server("127.0.0.1", 9502); $ws->set($setting); $ws->on('WorkerStart', array($object, 'onWorkerStart')); $ws->on('open', array($object, 'onOpen')); $ws->on('message', array($object, 'onMessage')); $ws->on('close', array($object, 'onClose')); $ws->start(); class ChatServer { /** @var Redis */ private $redis; public function __construct() { echo "启动前清理数据\n"; $redis = new Redis(); $redis->connect('127.0.0.1', 6379); if ($redis->ping() != '+PONG') { echo "redis连接失败\n";exit; } $delKeys = $redis->keys('fd_*'); foreach ($delKeys as $key) { $redis->del($key); } $delKeys = $redis->keys('roomId_*'); foreach ($delKeys as $key) { $redis->del($key); } } public function onWorkerStart($ws, $workerId) { $redis = new Redis(); $redis->connect('127.0.0.1', 6379); if ($redis->ping() != '+PONG') { echo "redis连接失败\n"; } $this->redis = $redis; } public function onOpen($ws, $request) { echo "fd:{$request->fd} is open\n"; if (empty($request->get['roomId']) || empty($request->get['nick'])) { $status = 'fail'; } else { //建立身份关联 $this->redis->hSet("fd_".$request->fd, 'roomId', $request->get['roomId']); $this->redis->hSet("fd_".$request->fd, 'nick', $request->get['nick']); $this->redis->sAdd("roomId_".$request->get['roomId'], $request->fd); $status = 'success'; } $sendData = [ 'cmd' => 'open', 'data' => [ 'status' => $status ] ]; $ws->push($request->fd, json_encode($sendData)); } public function onMessage($ws, $frame) { echo "fd:[$frame->fd}, Message: {$frame->data}\n"; if (!empty($frame->data)) { $fdInfo = $this->redis->hGetAll("fd_".$frame->fd); if (!empty($fdInfo['nick']) && !empty($fdInfo['roomId'])) { $sendData = [ 'cmd' => 'ReceiveMessage', 'data' => [ 'nick' => $fdInfo['nick'], 'msg' => $frame->data, ] ]; $fdArr = $this->redis->sMembers("roomId_".$fdInfo['roomId']); foreach ($fdArr as $fd) { $ws->push($fd, json_encode($sendData)); } } } } public function onClose($ws, $fd, $reactorId) { echo "fd:{$fd} is closed\n"; //删除fd身份数据并在房间内移动该fd $fdInfo = $this->redis->hGetAll("fd_".$fd); if (!empty($fdInfo['roomId'])) { $this->redis->sRem("roomId_".$fdInfo['roomId'], $fd); } $this->redis->del("fd_".$fd); } }
注意事项:
1.Worker进程之间不能共享变量,这里使用Redis来共享数据。
2.Worker进程不能共用同一个Redis客户端,需要放到onWorkerStart中实例化。
3.客户端可使用JS内置等WebSokcet客户端,异步的PHP程序可使用Swoole\Http\Client,同步可以使用swoole/framework提供的同步WebSocket客户端。
使用Swoole提供HTTP服务,模拟官方Swoole框架实现一个简易框架。
PHP主代码:
<?php $object = new AppServer(); $setting = [ 'log_file' => 'swoole_http.log', 'worker_num' => 4, // 4个工作进程 ]; $server = new swoole_http_server("127.0.0.1", 9503); $server->set($setting); $server->on('request', array($object, 'onRequest')); $server->on('close', array($object, 'onClose')); $server->start(); /** * Class AppServer * @property \swoole_http_request $request * @property \swoole_http_response $response * @property \PDO $db * @property \lib\Session $session */ class AppServer { private $module = []; /** @var AppServer */ private static $instance; public static function getInstance() { return self::$instance; } public function __construct() { $baseControllerFile = __DIR__ .'/controller/Base.php'; require_once "$baseControllerFile"; } /** * @param swoole_http_request $request * @param swoole_http_response $response */ public function onRequest($request, $response) { $this->module['request'] = $request; $this->module['response'] = $response; self::$instance = $this; list($controllerName, $methodName) = $this->route($request); empty($controllerName) && $controllerName = 'index'; empty($methodName) && $methodName = 'index'; try { $controllerClass = "\\controller\\" . ucfirst($controllerName); $controllerFile = __DIR__ . "/controller/" . ucfirst($controllerName) . ".php"; if (!class_exists($controllerClass, false)) { if (!is_file($controllerFile)) { throw new Exception('控制器不存在'); } require_once "$controllerFile"; } $controller = new $controllerClass($this); if (!method_exists($controller, $methodName)) { throw new Exception('控制器方法不存在'); } ob_start(); $return = $controller->$methodName(); $return .= ob_get_contents(); ob_end_clean(); $this->session->end(); $response->end($return); } catch (Exception $e) { $response->status(500); $response->end($e->getMessage()); } } private function route($request) { $pathInfo = explode('/', $request->server['path_info']); return [$pathInfo[1], $pathInfo[2]]; } public function onClose($server, $fd, $reactorId) { } public function __get($name) { if (!in_array($name, array('request', 'response', 'db', 'session'))) { return null; } if (empty($this->module[$name])) { $moduleClass = "\\lib\\" . ucfirst($name); $moduleFile = __DIR__ . '/lib/' . ucfirst($name) . ".php"; if (is_file($moduleFile)) { require_once "$moduleFile"; $object = new $moduleClass; $this->module[$name] = $object; } } return $this->module[$name]; } }
使用header和setCooike示例:
<?php namespace controller; class Http extends Base { public function header() { //发送Http状态码,如500, 404等等 $this->response->status(302); //使用此函数代替PHP的header函数 $this->response->header('Location', 'http://www.baidu.com/'); } public function cookie() { $this->response->cookie('http_cookie','http_cookie_value'); } }
Session实现:
<?php namespace lib; class Session { private $sessionId; private $cookieKey; private $storeDir; private $file; private $isStart; public function __construct() { $this->cookieKey = 'PHPSESSID'; $this->storeDir = 'tmp/'; $this->isStart = false; } public function start() { $this->isStart = true; $appServer = \AppServer::getInstance(); $request = $appServer->request; $response = $appServer->response; $sessionId = $request->cookie[$this->cookieKey]; if (empty($sessionId)){ $sessionId = uniqid(); $response->cookie($this->cookieKey, $sessionId); } $this->sessionId = $sessionId; $storeFile = $this->storeDir . $sessionId; if (!is_file($storeFile)) { touch($storeFile); } $session = $this->get($storeFile); $_SESSION = $session; } public function end() { $this->save(); } public function commit() { $this->save(); } private function save() { if ($this->isStart) { $data = json_encode($_SESSION); ftruncate($this->file, 0); if ($data) { rewind($this->file); fwrite($this->file, $data); } flock($this->file, LOCK_UN); fclose($this->file); } } private function get($fileName) { $this->file = fopen($fileName, 'c+b'); if(flock($this->file, LOCK_EX | LOCK_NB)) { $data = []; clearstatcache(); if (filesize($fileName) > 0) { $data = fread($this->file, filesize($fileName)); $data = json_decode($data, true); } return $data; } } }
注意事项:
使用Redis/MySQL等客户端理应使用线程池,参照官方Swoole框架。
Swoole是在执行PHP文件这一阶段进行接管,因此header,setCooike,seesion_start不可用,header和setCooike可用$response变量实现,Session可自行实现。
以上是“Swoole如何使用”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。