首頁 > php框架 > Swoole > 一起學習Swoole的簡單運用實作例子

一起學習Swoole的簡單運用實作例子

coldplay.xixi
發布: 2021-04-26 16:53:21
轉載
2596 人瀏覽過

一起學習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

安装

按照官方文档进行安装:Swoole官网,安装完后使用命令:

php -m
登入後複製

查看是否安装成功。注意:Swoole从2.0版本开始支持了内置协程,需使用PHP7。

基于TCP的邮件服务器

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

邮件功能:

PHPMailer

PHP主代码:

<?php

$object = new MailServer();

$setting = [
    &#39;log_file&#39; => &#39;swoole.log&#39;,
    &#39;worker_num&#39; => 4, // 4个工作进程
    &#39;task_worker_num&#39; => 10, // 10个任务进程
];
$server = new swoole_server("127.0.0.1", 9501);
$server->set($setting);

$server->on(&#39;WorkerStart&#39;, array($object, &#39;onWorkerStart&#39;));
$server->on(&#39;Connect&#39;, array($object, &#39;onConnect&#39;));
$server->on(&#39;Receive&#39;, array($object, &#39;onReceive&#39;));
$server->on(&#39;Close&#39;, array($object, &#39;onClose&#39;));
$server->on(&#39;Task&#39;, array($object, &#39;onTask&#39;));
$server->on(&#39;Finish&#39;, array($object, &#39;onFinish&#39;));

$server->start();

class MailServer
{
    /** @var Mail */
    private $handle;

    public function __construct()
    {
        require &#39;Mail.php&#39;; // PHPMailer邮件服务类
    }

    public function onWorkerStart($server, $workerId)
    {
        $mailConfig = require &#39;MailConfig.php&#39;; // 发件人信息,重启时会重新加载配置文件
        $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[&#39;address&#39;]) || empty($dataArr[&#39;subject&#39;]) || empty($dataArr[&#39;body&#39;])) {
            $return[&#39;code&#39;] = -1;
            $return[&#39;msg&#39;] = &#39;参数不能为空&#39;;
        } else { // 参数校验成功
            $server->task($data); // 投递一个任务
            $return[&#39;code&#39;] = 0;
            $return[&#39;msg&#39;] = &#39;投递任务成功&#39;;
        }
        $server->send($fd, json_encode($return));
    }

    public function onTask($server, $taskId, $workerId, $data)
    {
        $data = json_decode($data, true);
        $this->handle->send($data[&#39;address&#39;], $data[&#39;subject&#39;], $data[&#39;body&#39;]); // 发送邮件
    }

    public function onFinish($server, $task_id, $data)
    {

    }

    public function onClose($server, $fd, $reactorId)
    {

    }
}
登入後複製

发件人信息配置:

<?php

// 邮件发送人信息配置

return [
    &#39;host&#39; => &#39;smtp.qq.com&#39;,
    &#39;port&#39; => &#39;465&#39;,
    &#39;fromName&#39; => &#39;Mr.litt&#39;,
    &#39;username&#39; => &#39;137057181@qq.com&#39;,
    &#39;password&#39; => &#39;&#39;,
];
登入後複製

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 PHPMailer\PHPMailer\PHPMailer;

class Mail
{
    private $host;
    private $port;
    private $fromName;
    private $username;
    private $password;

    public function __construct($config)
    {
        !empty($config[&#39;host&#39;]) && $this->host = $config[&#39;host&#39;];
        !empty($config[&#39;port&#39;]) && $this->port = $config[&#39;port&#39;];
        !empty($config[&#39;fromName&#39;]) && $this->fromName = $config[&#39;fromName&#39;];
        !empty($config[&#39;username&#39;]) && $this->username = $config[&#39;username&#39;];
        !empty($config[&#39;password&#39;]) && $this->password = $config[&#39;password&#39;];
        if (empty($this->host) || empty($this->port) || empty($this->fromName) ||
            empty($this->username) || empty($this->password)) {
            throw new Exception(&#39;发件人信息错误&#39;);
        }
    }

    public function send($address, $subject, $body)
    {
        if (empty($address) || empty($subject) || empty($body)) {
            throw new Exception(&#39;收件人信息错误&#39;);
        }
        // 实例化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 = &#39;ssl&#39;;
        // 设置ssl连接smtp服务器的远程服务器端口号
        $mail->Port = $this->port;
        // 设置发送的邮件的编码
        $mail->CharSet = &#39;UTF-8&#39;;
        // 设置发件人昵称 显示在收件人邮件的发件人邮箱地址前的发件人姓名
        $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(&#39;87654321@163.com&#39;);
        // 添加该邮件的主题
        $mail->Subject = $subject;
        // 添加邮件正文
        $mail->Body = $body;
        // 为该邮件添加附件
        //$mail->addAttachment(&#39;./example.pdf&#39;);
        // 发送邮件 返回状态
        $status = $mail->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; => &#39;swoole_ws.log&#39;,
    &#39;worker_num&#39; => 4, // 4个工作进程
];
$ws = new swoole_websocket_server("127.0.0.1", 9502);
$ws->set($setting);

$ws->on(&#39;WorkerStart&#39;, array($object, &#39;onWorkerStart&#39;));
$ws->on(&#39;open&#39;, array($object, &#39;onOpen&#39;));
$ws->on(&#39;message&#39;, array($object, &#39;onMessage&#39;));
$ws->on(&#39;close&#39;, array($object, &#39;onClose&#39;));

$ws->start();

class ChatServer
{
    /** @var  Redis */
    private $redis;

    public function __construct()
    {
        echo "启动前清理数据\n";
        $redis = new Redis();
        $redis->connect(&#39;127.0.0.1&#39;, 6379);
        if ($redis->ping() != &#39;+PONG&#39;) {
            echo "redis连接失败\n";exit;
        }
        $delKeys = $redis->keys(&#39;fd_*&#39;);
        foreach ($delKeys as $key) {
            $redis->del($key);
        }
        $delKeys = $redis->keys(&#39;roomId_*&#39;);
        foreach ($delKeys as $key) {
            $redis->del($key);
        }
    }

    public function onWorkerStart($ws, $workerId)
    {
        $redis = new Redis();
        $redis->connect(&#39;127.0.0.1&#39;, 6379);
        if ($redis->ping() != &#39;+PONG&#39;) {
            echo "redis连接失败\n";
        }
        $this->redis = $redis;
    }

    public function onOpen($ws, $request)
    {
        echo "fd:{$request->fd} is open\n";
        if (empty($request->get[&#39;roomId&#39;]) || empty($request->get[&#39;nick&#39;])) {
            $status = &#39;fail&#39;;
        } else {
            //建立身份关联
            $this->redis->hSet("fd_".$request->fd, &#39;roomId&#39;, $request->get[&#39;roomId&#39;]);
            $this->redis->hSet("fd_".$request->fd, &#39;nick&#39;, $request->get[&#39;nick&#39;]);
            $this->redis->sAdd("roomId_".$request->get[&#39;roomId&#39;], $request->fd);

            $status = &#39;success&#39;;
        }
        $sendData = [
            &#39;cmd&#39; => &#39;open&#39;,
            &#39;data&#39; => [
                &#39;status&#39; => $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[&#39;nick&#39;]) && !empty($fdInfo[&#39;roomId&#39;])) {
                $sendData = [
                    &#39;cmd&#39; => &#39;ReceiveMessage&#39;,
                    &#39;data&#39; => [
                        &#39;nick&#39; => $fdInfo[&#39;nick&#39;],
                        &#39;msg&#39; => $frame->data,
                    ]
                ];
                $fdArr = $this->redis->sMembers("roomId_".$fdInfo[&#39;roomId&#39;]);
                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[&#39;roomId&#39;])) {
            $this->redis->sRem("roomId_".$fdInfo[&#39;roomId&#39;], $fd);
        }
        $this->redis->del("fd_".$fd);
    }
}
登入後複製

注意事项:

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

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

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

基于HTTP的简易框架

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

PHP主代码:

<?php

$object = new AppServer();

$setting = [
    &#39;log_file&#39; => &#39;swoole_http.log&#39;,
    &#39;worker_num&#39; => 4, // 4个工作进程
];
$server = new swoole_http_server("127.0.0.1", 9503);
$server->set($setting);

$server->on(&#39;request&#39;, array($object, &#39;onRequest&#39;));
$server->on(&#39;close&#39;, array($object, &#39;onClose&#39;));

$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__ .&#39;/controller/Base.php&#39;;
        require_once "$baseControllerFile";
    }

    /**
     * @param swoole_http_request $request
     * @param swoole_http_response $response
     */
    public function onRequest($request, $response)
    {
        $this->module[&#39;request&#39;] = $request;
        $this->module[&#39;response&#39;] = $response;
        self::$instance = $this;

        list($controllerName, $methodName) = $this->route($request);
        empty($controllerName) && $controllerName = &#39;index&#39;;
        empty($methodName) && $methodName = &#39;index&#39;;

        try {
            $controllerClass = "\\controller\\" . ucfirst($controllerName);
            $controllerFile = __DIR__ . "/controller/" . ucfirst($controllerName) . ".php";
            if (!class_exists($controllerClass, false)) {
                if (!is_file($controllerFile)) {
                    throw new Exception(&#39;控制器不存在&#39;);
                }
                require_once "$controllerFile";
            }

            $controller = new $controllerClass($this);
            if (!method_exists($controller, $methodName)) {
                throw new Exception(&#39;控制器方法不存在&#39;);
            }

            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(&#39;/&#39;, $request->server[&#39;path_info&#39;]);
        return [$pathInfo[1], $pathInfo[2]];
    }

    public function onClose($server, $fd, $reactorId)
    {

    }

    public function __get($name)
    {
        if (!in_array($name, array(&#39;request&#39;, &#39;response&#39;, &#39;db&#39;, &#39;session&#39;))) {
            return null;
        }
        if (empty($this->module[$name])) {
            $moduleClass = "\\lib\\" . ucfirst($name);
            $moduleFile = __DIR__ . &#39;/lib/&#39; . 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(&#39;Location&#39;, &#39;http://www.baidu.com/&#39;);
    }

    public function cookie()
    {
        $this->response->cookie(&#39;http_cookie&#39;,&#39;http_cookie_value&#39;);
    }
}
登入後複製

Session实现:

<?php

namespace lib;

class Session
{
    private $sessionId;
    private $cookieKey;
    private $storeDir;
    private $file;
    private $isStart;

    public function __construct()
    {
        $this->cookieKey = &#39;PHPSESSID&#39;;
        $this->storeDir = &#39;tmp/&#39;;
        $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, &#39;c+b&#39;);
        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;
        }
    }
}
登入後複製

注意事项:

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

总结

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

以上是一起學習Swoole的簡單運用實作例子的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:csdn.net
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板