介绍Swoole的简单运用实现例子

Swoole框架栏目介绍介绍swoole的简单运用实现例子

介绍Swoole的简单运用实现例子

推荐(免费):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。

基于TCP的邮件服务器

使用Swoole提供TCP服务,异步任务发送邮件。

邮件功能:

PHPMailer

PHP主代码:

<?php $object = new MailServer();  $setting = [     &#39;log_file&#39; => 'swoole.log',     'worker_num' =&gt; 4, // 4个工作进程     'task_worker_num' =&gt; 10, // 10个任务进程 ]; $server = new swoole_server("127.0.0.1", 9501); $server-&gt;set($setting);  $server-&gt;on('WorkerStart', array($object, 'onWorkerStart')); $server-&gt;on('Connect', array($object, 'onConnect')); $server-&gt;on('Receive', array($object, 'onReceive')); $server-&gt;on('Close', array($object, 'onClose')); $server-&gt;on('Task', array($object, 'onTask')); $server-&gt;on('Finish', array($object, 'onFinish'));  $server-&gt;start();  class MailServer {     /** @var Mail */     private $handle;      public function __construct()     {         require 'Mail.php'; // PHPMailer邮件服务类     }      public function onWorkerStart($server, $workerId)     {         $mailConfig = require 'MailConfig.php'; // 发件人信息,重启时会重新加载配置文件         $this-&gt;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-&gt;task($data); // 投递一个任务             $return['code'] = 0;             $return['msg'] = '投递任务成功';         }         $server-&gt;send($fd, json_encode($return));     }      public function onTask($server, $taskId, $workerId, $data)     {         $data = json_decode($data, true);         $this-&gt;handle-&gt;send($data['address'], $data['subject'], $data['body']); // 发送邮件     }      public function onFinish($server, $task_id, $data)     {      }      public function onClose($server, $fd, $reactorId)     {      } }

发件人信息配置:

<?php // 邮件发送人信息配置  return [     &#39;host&#39; => 'smtp.qq.com',     'port' =&gt; '465',     'fromName' =&gt; 'Mr.litt',     'username' =&gt; '137057181@qq.com',     'password' =&gt; '', ];

PHPMailer邮件服务类:

<?php require &#39;vendor/phpmailer/phpmailer/src/Exception.php&#39;; require &#39;vendor/phpmailer/phpmailer/src/PHPMailer.php&#39;; require &#39;vendor/phpmailer/phpmailer/src/SMTP.php&#39;;  use PHPMailerPHPMailerPHPMailer;  class Mail {     private $host;     private $port;     private $fromName;     private $username;     private $password;      public function __construct($config)     {         !empty($config[&#39;host&#39;]) && $this->host = $config['host'];         !empty($config['port']) &amp;&amp; $this-&gt;port = $config['port'];         !empty($config['fromName']) &amp;&amp; $this-&gt;fromName = $config['fromName'];         !empty($config['username']) &amp;&amp; $this-&gt;username = $config['username'];         !empty($config['password']) &amp;&amp; $this-&gt;password = $config['password'];         if (empty($this-&gt;host) || empty($this-&gt;port) || empty($this-&gt;fromName) ||             empty($this-&gt;username) || empty($this-&gt;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-&gt;SMTPDebug = 0;         // 使用smtp鉴权方式发送邮件         $mail-&gt;isSMTP();         // smtp需要鉴权 这个必须是true         $mail-&gt;SMTPAuth = true;         // 链接邮箱的服务器地址         $mail-&gt;Host = $this-&gt;host;         // 设置使用ssl加密方式登录鉴权         $mail-&gt;SMTPSecure = 'ssl';         // 设置ssl连接smtp服务器的远程服务器端口号         $mail-&gt;Port = $this-&gt;port;         // 设置发送的邮件的编码         $mail-&gt;CharSet = 'UTF-8';         // 设置发件人昵称 显示在收件人邮件的发件人邮箱地址前的发件人姓名         $mail-&gt;FromName = $this-&gt;fromName;         // smtp登录的账号 QQ邮箱即可         $mail-&gt;Username = $this-&gt;username;         // smtp登录的密码 使用生成的授权码         $mail-&gt;Password = $this-&gt;password;         // 设置发件人邮箱地址 同登录账号         $mail-&gt;From = $this-&gt;username;         // 邮件正文是否为html编码 注意此处是一个方法         $mail-&gt;isHTML(true);         // 设置收件人邮箱地址         $mail-&gt;addAddress($address);         // 添加多个收件人 则多次调用方法即可         //$mail-&gt;addAddress('87654321@163.com');         // 添加该邮件的主题         $mail-&gt;Subject = $subject;         // 添加邮件正文         $mail-&gt;Body = $body;         // 为该邮件添加附件         //$mail-&gt;addAttachment('./example.pdf');         // 发送邮件 返回状态         $status = $mail-&gt;send();         return $status;     } }

注意事项:

  1. 修改发件人信息后,只需重启task_worker就生效,命令 kill -USER1 主进程PID。
  2. TCP客户端可使用swoole_client类来模拟。
  3. 短信、推送等异步任务同样适用于此场景。

基于WebSocket多房间聊天功能

使用Swoole提供WebSocket服务,使用Redis保存房间人员信息。

PHP主代码:

<?php $object = new ChatServer();  $setting = [     &#39;log_file&#39; => 'swoole_ws.log',     'worker_num' =&gt; 4, // 4个工作进程 ]; $ws = new swoole_websocket_server("127.0.0.1", 9502); $ws-&gt;set($setting);  $ws-&gt;on('WorkerStart', array($object, 'onWorkerStart')); $ws-&gt;on('open', array($object, 'onOpen')); $ws-&gt;on('message', array($object, 'onMessage')); $ws-&gt;on('close', array($object, 'onClose'));  $ws-&gt;start();  class ChatServer {     /** @var  Redis */     private $redis;      public function __construct()     {         echo "启动前清理数据 ";         $redis = new Redis();         $redis-&gt;connect('127.0.0.1', 6379);         if ($redis-&gt;ping() != '+PONG') {             echo "redis连接失败 ";exit;         }         $delKeys = $redis-&gt;keys('fd_*');         foreach ($delKeys as $key) {             $redis-&gt;del($key);         }         $delKeys = $redis-&gt;keys('roomId_*');         foreach ($delKeys as $key) {             $redis-&gt;del($key);         }     }      public function onWorkerStart($ws, $workerId)     {         $redis = new Redis();         $redis-&gt;connect('127.0.0.1', 6379);         if ($redis-&gt;ping() != '+PONG') {             echo "redis连接失败 ";         }         $this-&gt;redis = $redis;     }      public function onOpen($ws, $request)     {         echo "fd:{$request-&gt;fd} is open ";         if (empty($request-&gt;get['roomId']) || empty($request-&gt;get['nick'])) {             $status = 'fail';         } else {             //建立身份关联             $this-&gt;redis-&gt;hSet("fd_".$request-&gt;fd, 'roomId', $request-&gt;get['roomId']);             $this-&gt;redis-&gt;hSet("fd_".$request-&gt;fd, 'nick', $request-&gt;get['nick']);             $this-&gt;redis-&gt;sAdd("roomId_".$request-&gt;get['roomId'], $request-&gt;fd);              $status = 'success';         }         $sendData = [             'cmd' =&gt; 'open',             'data' =&gt; [                 'status' =&gt; $status             ]         ];         $ws-&gt;push($request-&gt;fd, json_encode($sendData));     }      public function onMessage($ws, $frame)     {         echo "fd:[$frame-&gt;fd}, Message: {$frame-&gt;data} ";         if (!empty($frame-&gt;data)) {             $fdInfo = $this-&gt;redis-&gt;hGetAll("fd_".$frame-&gt;fd);             if (!empty($fdInfo['nick']) &amp;&amp; !empty($fdInfo['roomId'])) {                 $sendData = [                     'cmd' =&gt; 'ReceiveMessage',                     'data' =&gt; [                         'nick' =&gt; $fdInfo['nick'],                         'msg' =&gt; $frame-&gt;data,                     ]                 ];                 $fdArr = $this-&gt;redis-&gt;sMembers("roomId_".$fdInfo['roomId']);                 foreach ($fdArr as $fd) {                     $ws-&gt;push($fd, json_encode($sendData));                 }             }         }     }      public function onClose($ws, $fd, $reactorId)     {         echo "fd:{$fd} is closed ";         //删除fd身份数据并在房间内移动该fd         $fdInfo = $this-&gt;redis-&gt;hGetAll("fd_".$fd);         if (!empty($fdInfo['roomId'])) {             $this-&gt;redis-&gt;sRem("roomId_".$fdInfo['roomId'], $fd);         }         $this-&gt;redis-&gt;del("fd_".$fd);     } }

注意事项:

1.Worker进程之间不能共享变量,这里使用Redis来共享数据。

2.Worker进程不能共用同一个Redis客户端,需要放到onWorkerStart中实例化。

3.客户端可使用JS内置等WebSokcet客户端,异步的PHP程序可使用SwooleHttpClient,同步可以使用swoole/framework提供的同步WebSocket客户端。

基于HTTP的简易框架

使用Swoole提供HTTP服务,模拟官方Swoole框架实现一个简易框架。

PHP主代码:

<?php $object = new AppServer();  $setting = [     &#39;log_file&#39; => 'swoole_http.log',     'worker_num' =&gt; 4, // 4个工作进程 ]; $server = new swoole_http_server("127.0.0.1", 9503); $server-&gt;set($setting);  $server-&gt;on('request', array($object, 'onRequest')); $server-&gt;on('close', array($object, 'onClose'));  $server-&gt;start();  /**  * Class AppServer  * @property swoole_http_request $request  * @property swoole_http_response $response  * @property PDO $db  * @property libSession $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-&gt;module['request'] = $request;         $this-&gt;module['response'] = $response;         self::$instance = $this;          list($controllerName, $methodName) = $this-&gt;route($request);         empty($controllerName) &amp;&amp; $controllerName = 'index';         empty($methodName) &amp;&amp; $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-&gt;$methodName();             $return .= ob_get_contents();             ob_end_clean();             $this-&gt;session-&gt;end();             $response-&gt;end($return);         } catch (Exception $e) {             $response-&gt;status(500);             $response-&gt;end($e-&gt;getMessage());         }     }      private function route($request)     {         $pathInfo = explode('/', $request-&gt;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-&gt;module[$name])) {             $moduleClass = "lib" . ucfirst($name);             $moduleFile = __DIR__ . '/lib/' . ucfirst($name) . ".php";             if (is_file($moduleFile)) {                 require_once "$moduleFile";                 $object = new $moduleClass;                 $this-&gt;module[$name] = $object;             }         }         return $this-&gt;module[$name];     } }

使用header和setCooike示例:

<?php namespace controller;  class Http extends Base {     public function header()     {         //发送Http状态码,如500, 404等等         $this->response-&gt;status(302);         //使用此函数代替PHP的header函数         $this-&gt;response-&gt;header('Location', 'http://www.baidu.com/');     }      public function cookie()     {         $this-&gt;response-&gt;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-&gt;storeDir = 'tmp/';         $this-&gt;isStart = false;     }      public function start()     {         $this-&gt;isStart = true;         $appServer = AppServer::getInstance();         $request = $appServer-&gt;request;         $response = $appServer-&gt;response;         $sessionId = $request-&gt;cookie[$this-&gt;cookieKey];         if (empty($sessionId)){             $sessionId = uniqid();             $response-&gt;cookie($this-&gt;cookieKey, $sessionId);         }         $this-&gt;sessionId = $sessionId;         $storeFile = $this-&gt;storeDir . $sessionId;         if (!is_file($storeFile)) {             touch($storeFile);         }         $session = $this-&gt;get($storeFile);         $_SESSION = $session;     }      public function end()     {         $this-&gt;save();     }      public function commit()     {         $this-&gt;save();     }      private function save()     {         if ($this-&gt;isStart) {             $data = json_encode($_SESSION);             ftruncate($this-&gt;file, 0);              if ($data) {                 rewind($this-&gt;file);                 fwrite($this-&gt;file, $data);             }             flock($this-&gt;file, LOCK_UN);             fclose($this-&gt;file);         }     }      private function get($fileName)     {         $this-&gt;file = fopen($fileName, 'c+b');         if(flock($this-&gt;file, LOCK_EX | LOCK_NB)) {             $data = [];             clearstatcache();             if (filesize($fileName) &gt; 0) {                 $data = fread($this-&gt;file, filesize($fileName));                 $data = json_decode($data, true);             }             return $data;         }     } }

注意事项:

  1. 使用Redis/MySQL等客户端理应使用线程池,参照官方Swoole框架。
  2. Swoole是在执行PHP文件这一阶段进行接管,因此header,setCooike,seesion_start不可用,header和setCooike可用$response变量实现,Session可自行实现。
  3. 推荐查看官方框架:Swoole框架。

上述demo可以戳这里:demo

总结

Swoole的应用远不如此,Swoole就像打开了PHP世界的新大门,我觉得每一位PHPer都应该学习和掌握Swoole的用法,能学到很多使用LAMP/LNMP模式时未涉及到的知识点。

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享