首页 > PHP学习 > 介绍EasySwoole安装使用

介绍EasySwoole安装使用

时间:2022年7月6日 分类:PHP学习 浏览量:321

EasySwoole

EasySwoole 是一款基于Swoole Server 开发的常驻内存型的分布式PHP框架,专为API而生,摆脱传统PHP运行模式在进程唤起和文件加载上带来的性能损失。 EasySwoole 高度封装了 Swoole Server 而依旧维持 Swoole Server 原有特性,支持同时混合监听HTTP、自定义TCP、UDP协议,让开发者以最低的学习成本和精力编写出多进程,可异步,高可用的应用服务

推荐(免费):swoole

安装

  • 保证 PHP 版本大于等于 7.1
  • 保证 Swoole 拓展版本大于等于 4.4.15
  • 需要 pcntl 拓展的任意版本
  • 使用 Linux / FreeBSD / MacOS 这三类操作系统
  • 使用 Composer 作为依赖管理工具

composer require easyswoole/easyswoole=3.x
php vendor/easyswoole/easyswoole/bin/easyswoole install

  • 新版的easyswoole安装会默认提供App命名空间,还有index控制器
  • 在这里面需要填写n,不需要覆盖,已经有的 EasySwooleEvent.phpindex.php dev.php produce.php
  • 当提示exec函数被禁用时,请自己手动执行 composer dump-autoload 命令更新命名空间

进入项目根目录执行程序,项目执行成功,访问页面

php easyswoole start
在这里插入图片描述

在这里插入图片描述

HTTP

HttpController为控制器根目录,访问会根据url自动映射到此目录的控制器中,Index作为默认控制器,index为默认方法
在这里插入图片描述

访问http://192.168.88.16:9501地址为默认访问到index.php控制器中index方法,即http://192.168.88.16:9501/index/index地址与tp框架的访问相类似

  • 我们在index控制器中新建一个hello方法,打印hello world,重新启动项目,访问http://192.168.88.16:9501/hellohttp://192.168.88.16:9501/index/hello页面都会打印hello world
<?phpnamespace App\HttpController;use EasySwoole\Http\AbstractInterface\Controller;class Index extends Controller{
 public function hello(){
        $this->response()->write('hello world');
    }

    public function index()
    {
        $file = EASYSWOOLE_ROOT.'/vendor/easyswoole/easyswoole/src/Resource/Http/welcome.html';
        if(!is_file($file)){
            $file = EASYSWOOLE_ROOT.'/src/Resource/Http/welcome.html';//欢迎页面
        }
        $this->response()->write(file_get_contents($file));
    }

    protected function actionNotFound(?string $action)
    {
        $this->response()->withStatus(404);
        $file = EASYSWOOLE_ROOT.'/vendor/easyswoole/easyswoole/src/Resource/Http/404.html';
        if(!is_file($file)){
            $file = EASYSWOOLE_ROOT.'/src/Resource/Http/404.html';
        }
        $this->response()->write(file_get_contents($file));
    }}

在这里插入图片描述

WebSocket

WebSocket协议在传统的phpweb框架就不适用了,在php中基本就使用workerman和swoole去解决这种场景,在easyswoole框架即是swoole的封装

  • dev.php配置文件,将服务类型SERVER_TYPE修改为EASYSWOOLE_WEB_SOCKET_SERVER,进行WebSocket通讯,EasySwooleEvent.php文件中,新增主服务增加onMessage事件监听消息
<?phpnamespace EasySwoole\EasySwoole;use EasySwoole\EasySwoole\Swoole\EventRegister;use EasySwoole\EasySwoole\AbstractInterface\Event;use EasySwoole\Http\Request;use EasySwoole\Http\Response;class EasySwooleEvent implements Event{

    public static function initialize()
    {
        // TODO: Implement initialize() method.
        date_default_timezone_set('Asia/Shanghai');
    }

    public static function mainServerCreate(EventRegister $register)
    {
        // TODO: Implement mainServerCreate() method.\
        $register->set(EventRegister::onMessage,function (\swoole_websocket_server $server, \swoole_websocket_frame $frame){
            var_dump($frame);
        });
    }

    public static function onRequest(Request $request, Response $response): bool    {
        // TODO: Implement onRequest() method.
        return true;
    }

    public static function afterRequest(Request $request, Response $response): void    {
        // TODO: Implement afterAction() method.
    }}
  • 使用easyswoole的测试工具进行连接测试
    在这里插入图片描述
    在这里插入图片描述

WebSocket控制器

在WebSocket,一般都是在一个onmessage中写响应代码,业务复杂的情况下一个方法中非常的冗长,easyswoole提供一种类似控制器方式的写法,这里已官方的例子为例:

  • 安装拓展包

composer require easyswoole/socket

dev.php,修改SERVER_TYPE为:

‘SERVER_TYPE’ => EASYSWOOLE_WEB_SOCKET_SERVER,

注册服务:

public static function mainServerCreate(EventRegister $register): void{
    /**
     * **************** websocket控制器 **********************
     */
    // 创建一个 Dispatcher 配置
    $conf = new \EasySwoole\Socket\Config();
    // 设置 Dispatcher 为 WebSocket 模式
    $conf->setType(\EasySwoole\Socket\Config::WEB_SOCKET);
    // 设置解析器对象
    $conf->setParser(new WebSocketParser());
    // 创建 Dispatcher 对象 并注入 config 对象
    $dispatch = new Dispatcher($conf);
    // 给server 注册相关事件 在 WebSocket 模式下  on message 事件必须注册 并且交给 Dispatcher 对象处理
    $register->set(EventRegister::onMessage, function (\swoole_websocket_server $server, \swoole_websocket_frame $frame) use ($dispatch) {
        $dispatch->dispatch($server, $frame->data, $frame);
    });}

创建App/WebSocket/WebSocketParser.php文件

namespace App\WebSocket;use EasySwoole\Socket\AbstractInterface\ParserInterface;use EasySwoole\Socket\Client\WebSocket;use EasySwoole\Socket\Bean\Caller;use EasySwoole\Socket\Bean\Response;/**
 * Class WebSocketParser
 *
 * 此类是自定义的 websocket 消息解析器
 * 此处使用的设计是使用 json string 作为消息格式
 * 当客户端消息到达服务端时,会调用 decode 方法进行消息解析
 * 会将 websocket 消息 转成具体的 Class -> Action 调用 并且将参数注入
 *
 * @package App\WebSocket
 */class WebSocketParser implements ParserInterface{
    /**
     * decode
     * @param  string         $raw    客户端原始消息
     * @param  WebSocket      $client WebSocket Client 对象
     * @return Caller         Socket  调用对象
     */
    public function decode($raw, $client) : ? Caller    {
        // 解析 客户端原始消息
        $data = json_decode($raw, true);
        if (!is_array($data)) {
            echo "decode message error! \n";
            return null;
        }

        // new 调用者对象
        $caller =  new Caller();
        /**
         * 设置被调用的类 这里会将ws消息中的 class 参数解析为具体想访问的控制器
         * 如果更喜欢 event 方式 可以自定义 event 和具体的类的 map 即可
         * 注 目前 easyswoole 3.0.4 版本及以下 不支持直接传递 class string 可以通过这种方式
         */
        $class = '\\App\\WebSocket\\'. ucfirst($data['class'] ?? 'Index');
        $caller->setControllerClass($class);

        // 提供一个事件风格的写法//         $eventMap = [//             'index' => Index::class//         ];//         $caller->setControllerClass($eventMap[$data['class']] ?? Index::class);

        // 设置被调用的方法
        $caller->setAction($data['action'] ?? 'index');
        // 检查是否存在args
        if (!empty($data['content'])) {
            // content 无法解析为array 时 返回 content => string 格式
            $args = is_array($data['content']) ? $data['content'] : ['content' => $data['content']];
        }

        // 设置被调用的Args
        $caller->setArgs($args ?? []);
        return $caller;
    }
    /**
     * encode
     * @param  Response     $response Socket Response 对象
     * @param  WebSocket    $client   WebSocket Client 对象
     * @return string             发送给客户端的消息
     */
    public function encode(Response $response, $client) : ? string    {
        /**
         * 这里返回响应给客户端的信息
         * 这里应当只做统一的encode操作 具体的状态等应当由 Controller处理
         */
        return $response->getMessage();
    }}

创建App/WebSocket/Index.php文件

composer require easyswoole/task

<?php/**
 * Created by PhpStorm.
 * User: Apple
 * Date: 2018/11/1 0001
 * Time: 14:42
 */namespace App\WebSocket;use EasySwoole\EasySwoole\ServerManager;use EasySwoole\EasySwoole\Task\TaskManager;use EasySwoole\Socket\AbstractInterface\Controller;/**
 * Class Index
 *
 * 此类是默认的 websocket 消息解析后访问的 控制器
 *
 * @package App\WebSocket
 */class Index extends Controller{
    function hello()
    {
        $this->response()->setMessage('call hello with arg:'. json_encode($this->caller()->getArgs()));
    }

    public function who(){
        $this->response()->setMessage('your fd is '. $this->caller()->getClient()->getFd());
    }

    function delay()
    {
        $this->response()->setMessage('this is delay action');
        $client = $this->caller()->getClient();

        // 异步推送, 这里直接 use fd也是可以的
        TaskManager::getInstance()->async(function () use ($client){
            $server = ServerManager::getInstance()->getSwooleServer();
            $i = 0;
            while ($i < 5) {
                sleep(1);
                $server->push($client->getFd(),'push in http at '. date('H:i:s'));
                $i++;
            }
        });
    }}
  • websocket测试工具进行测试,进行提交的json自动到相应的控制器方法中进行处理
    在这里插入图片描述

觉得文章有用就打赏一下文章作者

微信扫一扫打赏

标签: