百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>网页制作> EasySwoole 根基入门
分享文章到:

EasySwoole 根基入门

发布时间:09/01 来源:未知 浏览: 关键词:

使用 Composer 安置

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

启动框架

php easyswoole start

nginx转发

server {
    root /data/wwwroot/;
    server_name local.easyswoole.com;
 
    location / {
        proxy_http_version 1.1;
        proxy_set_header Connection "keep-alive";
        proxy_set_header X-Real-IP $remote_addr;
        if (!-e $request_filename) {
             proxy_pass http://127.0.0.1:9501;
        }
        if (!-f $request_filename) {
             proxy_pass http://127.0.0.1:9501;
        }
    }
}

proxy_set_header X-Real-IP $remote_addr; 猎取真实IP地址

运转你的hellword

project              项目摆设名目
----------------------------------
├─App        利用名目
│  └─HttpController      利用的操纵器名目
│     └─Index.php    默许操纵器文件
----------------------------------

Index.php

<?php
namespace App\HttpController;
use EasySwoole\Http\AbstractInterface\Controller;
class Index extends Controller
{
    function index()
    {
        // TODO: Implement index() method.
        $this->response()->write('hello world');
    }
}

编纂根名目下的 composer.json 文件,注册利用的命名空间

{
    "autoload": {
        "psr-4": {
            "App\\": "App/"
        }
    },
    "require": {
        "easyswoole/easyswoole": "3.x-dev"
    }
}

意思就是设定主动加载

最后施行composer dumpautoload 命令更新命名空间,可以开端编写业务逻辑

# 更新命名空间映射
composer dumpautoload
# 启动框架
php easyswoole start
名目构造
project                   项目摆设名目
├─App                     利用名目(可以有多个)
│  ├─HttpController       操纵器名目
│  │  └─Index.php         默许操纵器
│  └─Model                模型文件名目
├─Log                     日志文件名目
├─Temp                    暂时文件名目
├─vendor                  第三方类库名目
├─composer.json           Composer架构
├─composer.lock           Composer锁定
├─EasySwooleEvent.php     框架全局事件
├─easyswoole              框架治理足本
├─easyswoole.install      框架安置锁定文件
├─dev.php                 开发配置文件
├─produce.php             生产配置文件

生命周期,也就是流程

10865887-bd0a50f622948627.png

配置文件说明

<?php
      /**
       * Created by PhpStorm.
       * User: yf
       * Date: 2019-01-01
       * Time: 20:06
       */
      return [
          'SERVER_NAME'   => "EasySwoole",//效劳名
          'MAIN_SERVER'   => [
              'LISTEN_ADDRESS' => '0.0.0.0',//监听地址
              'PORT'           => 9501,//监听端口
              'SERVER_TYPE'    => EASYSWOOLE_WEB_SERVER, //可选为 EASYSWOOLE_SERVER  EASYSWOOLE_WEB_SERVER EASYSWOOLE_WEB_SOCKET_SERVER
              'SOCK_TYPE'      => SWOOLE_TCP,//该配置项当为SERVER_TYPE值为TYPE_SERVER时有效
              'RUN_MODEL'      => SWOOLE_PROCESS,// 默许Server的运转模式
              'SETTING'        => [// Swoole Server的运转配置( 完全配置可见[Swoole文档](https://wiki.swoole.com/wiki/page/274.html) )
                  'worker_num'       => 8,//运转的  worker进程数目
                  'max_request'      => 5000,// worker 完成该数目的恳求后将退出,防止内存溢出
                  'task_worker_num'  => 8,//运转的 task_worker 进程数目
                  'task_max_request' => 1000,// task_worker 完成该数目的恳求后将退出,防止内存溢出
                  'reload_async' => true,//设定异步重新启动开关。设定为true时,将启用异步平安重新启动特性,Worker进程会等候异步事件完成后再退出。
                  'task_enable_coroutine' => true//开启后主动在onTask回调中创立协程
              ]
          ],
          'TEMP_DIR'      => null,//暂时文件存置的名目
          'LOG_DIR'       => null,//日志文件存置的名目
          'CONSOLE'       => [//console操纵台组件配置
              'ENABLE'         => true,//可否开启
              'LISTEN_ADDRESS' => '127.0.0.1',//监听地址
              'PORT'           => 9500,//监听端口
              'USER'           => 'root',//验权会员名
              'PASSWORD'       => '123456'//验权会员名
          ],
          'FAST_CACHE'    => [//fastCache组件
              'PROCESS_NUM' => 0,//进程数,大于0才开启
              'BACKLOG'     => 256,//数据队列缓冲区大小
          ],
          'DISPLAY_ERROR' => true,//可否开启错误显示
      ];

配置操纵类

EasySwoole\Config 类

toArray 办法猎取全部配置,load 办法重载全部配置

假如设定了修改,需要更新配置的意思

<?php
$instance = \EasySwoole\EasySwoole\Config::getInstance();
// 猎取配置 按层级用点号分隔
$instance->getConf('MAIN_SERVER.SETTING.task_worker_num');
// 设定配置 按层级用点号分隔
$instance->setConf('DATABASE.host', 'localhost');
// 猎取全部配置
$conf = $instance->getConf();
// 用一个数组覆盖当前配置项
$conf['DATABASE'] = [
    'host' => '127.0.0.1',
    'port' => 13306
];
$instance->load($conf);

增加会员配置项

'MYSQL' => [
    'host'          => '192.168.75.1',
    'port'          => '3306',
    'user'          => 'root',
    'timeout'       => '5',
    'charset'       => 'utf8mb4',
    'password'      => 'root',
    'database'      => 'cry',
    'POOL_MAX_NUM'  => '20',
    'POOL_TIME_OUT' => '0.1',
],
/*################ REDIS CONFIG ##################*/
'REDIS' => [
    'host'          => '127.0.0.1',
    'port'          => '6379',
    'auth'          => '',
    'POOL_MAX_NUM'  => '20',
    'POOL_MIN_NUM'  => '5',
    'POOL_TIME_OUT' => '0.1',
],

生产与开发配置别离

默许为开发模式,加载 dev.php

生成

php easyswoole start produce

DI注入配置

也就是依靠注入

<?php
Di::getInstance()->set(SysConst::ERROR_HANDLER,function (){});//配置错误处置回调
Di::getInstance()->set(SysConst::SHUTDOWN_FUNCTION,function (){});//配置足本完毕回调
Di::getInstance()->set(SysConst::HTTP_CONTROLLER_NAMESPACE,'App\\HttpController\\');//配置操纵器命名空间
Di::getInstance()->set(SysConst::HTTP_CONTROLLER_MAX_DEPTH,5);//配置http操纵器最大解析层级
Di::getInstance()->set(SysConst::HTTP_EXCEPTION_HANDLER,function (){});//配置http操纵器非常回调
Di::getInstance()->set(SysConst::HTTP_CONTROLLER_POOL_MAX_NUM,15);//http操纵器对象池最大数目

动态配置

每次开端了,是上一次的进程,比方你翻开了旧版,此刻更新了新版,但是旧版还是开着,没有重新启动动,也就是不断旧版,此刻有个动态配置,表示可以平滑的修改

<?php
    Config::getInstance()->setDynamicConf('test_config_value', 0);//配置一个动态配置项
    $test_config_value_1 = Config::getInstance()->getDynamicConf('test_config_value');//猎取一个配置
    Config::getInstance()->delDynamicConf('test_config_value');//删除一个配置

效劳治理足本

php easyswoole
 install       安置easySwoole
  start         启动easySwoole
  stop          休止easySwoole(守护模式下使用)
  reload        重新启动easySwoole(守护模式下使用)
  help          查看命令的帮忙信息
easyswoole help -start

守护模式启动

php easyswoole start d

线上

php easyswoole start produce

休止

php easyswoole stop

重新启动效劳

php easyswoole reload 只重新启动task进程
php easyswoole reload all  重新启动task + worker进程

文件热加载

由于 swoole 常驻内存的特性,修改文件后需要重新启动worker进程才能将被修改的文件从新载入内存中

解决:Process的方式实现文件变更主动停止效劳重载

创建文件 App/Process/HotReload.php 并增加如下内容,也可以放在其他位置,请对报命名空间

<?php
/**
 * Created by PhpStorm.
 * User: evalor
 * Date: 2018-11-26
 * Time: 23:18
 */
namespace App\Process;
use EasySwoole\Component\Process\AbstractProcess;
use EasySwoole\EasySwoole\ServerManager;
use EasySwoole\Utility\File;
use Swoole\Process;
use Swoole\Table;
use Swoole\Timer;
/**
 * 暴力热重载
 * Class HotReload
 * @package App\Process
 */
class HotReload extends AbstractProcess
{
    /** @var \swoole_table $table */
    protected $table;
    protected $isReady = false;
    protected $monitorDir; // 需要监控的名目
    protected $monitorExt; // 需要监控的后缀
    /**
     * 启动按时器停止轮回扫描
     */
    public function run($arg)
    {
        // 此处指定需要监视的名目 倡议只监视App名目下的文件变动
        $this->monitorDir = !empty($arg['monitorDir']) ? $arg['monitorDir'] : EASYSWOOLE_ROOT . '/App';
        // 指定需要监控的扩展名 不属于指定类型的的文件 疏忽变动 不重新启动
        $this->monitorExt = !empty($arg['monitorExt']) && is_array($arg['monitorExt']) ? $arg['monitorExt'] : ['php'];
        if (extension_loaded('inotify') && empty($arg['disableInotify'])) {
            // 扩展可用 优先使用扩展停止处置
            $this->registerInotifyEvent();
            echo "server hot reload start : use inotify\n";
        } else {
            // 扩展不成用时 停止暴力扫描
            $this->table = new Table(512);
            $this->table->column('mtime', Table::TYPE_INT, 4);
            $this->table->create();
            $this->runComparison();
            Timer::tick(1000, function () {
                $this->runComparison();
            });
            echo "server hot reload start : use timer tick comparison\n";
        }
    }
    /**
     * 扫描文件变动
     */
    private function runComparison()
    {
        $startTime = microtime(true);
        $doReload = false;
        $dirIterator = new \RecursiveDirectoryIterator($this->monitorDir);
        $iterator = new \RecursiveIteratorIterator($dirIterator);
        $inodeList = array();
        // 迭代名目全部文件停止检查
        foreach ($iterator as $file) {
            /** @var \SplFileInfo $file */
            $ext = $file->getExtension();
            if (!in_array($ext, $this->monitorExt)) {
                continue; // 只检查指定类型
            } else {
                // 由于修改文件名称 并不需要从新载入 可以基于inode停止监控
                $inode = $file->getInode();
                $mtime = $file->getMTime();
                array_push($inodeList, $inode);
                if (!$this->table->exist($inode)) {
                    // 创建文件或修改文件 变动了inode
                    $this->table->set($inode, ['mtime' => $mtime]);
                    $doReload = true;
                } else {
                    // 修改文件 但未发生inode变动
                    $oldTime = $this->table->get($inode)['mtime'];
                    if ($oldTime != $mtime) {
                        $this->table->set($inode, ['mtime' => $mtime]);
                        $doReload = true;
                    }
                }
            }
        }
        foreach ($this->table as $inode => $value) {
            // 迭代table寻觅需要删除的inode
            if (!in_array(intval($inode), $inodeList)) {
                $this->table->del($inode);
                $doReload = true;
            }
        }
        if ($doReload) {
            $count = $this->table->count();
            $time = date('Y-m-d H:i:s');
            $usage = round(microtime(true) - $startTime, 3);
            if (!$this->isReady == false) {
                // 监测到需要停止热重新启动
                echo "severReload at {$time} use : {$usage} s total: {$count} files\n";
                ServerManager::getInstance()->getSwooleServer()->reload();
            } else {
                // 首次扫描不需要停止重新启动操纵
                echo "hot reload ready at {$time} use : {$usage} s total: {$count} files\n";
                $this->isReady = true;
            }
        }
    }
    /**
     * 注册Inotify监听事件
     */
    private function registerInotifyEvent()
    {
        // 由于进程独立 且当前是自定义进程 全局变量只要该进程使用
        // 在肯定不会造成污染的状况下 也可以合理使用全局变量
        global $lastReloadTime;
        global $inotifyResource;
        $lastReloadTime = 0;
        $files = File::scanDirectory(EASYSWOOLE_ROOT . '/App');
        $files = array_merge($files['files'], $files['dirs']);
        $inotifyResource = inotify_init();
        // 为当前所有的名目和文件增加事件监听
        foreach ($files as $item) {
            inotify_add_watch($inotifyResource, $item, IN_CREATE | IN_DELETE | IN_MODIFY);
        }
        // 参加事件轮回
        swoole_event_add($inotifyResource, function () {
            global $lastReloadTime;
            global $inotifyResource;
            $events = inotify_read($inotifyResource);
            if ($lastReloadTime < time() && !empty($events)) { // 限制1s内不克不及停止反复reload
                $lastReloadTime = time();
                ServerManager::getInstance()->getSwooleServer()->reload();
            }
        });
    }
    public function onShutDown()
    {
        // TODO: Implement onShutDown() method.
    }
    public function onReceive(string $str)
    {
        // TODO: Implement onReceive() method.
    }
}

增加好后在全局的 EasySwooleEvent.php 中,注册该自定义进程

public static function mainServerCreate(EventRegister $register)
{
    $swooleServer = ServerManager::getInstance()->getSwooleServer();
    $swooleServer->addProcess((new HotReload('HotReload', ['disableInotify' => false]))->getProcess());
}

以上就是EasySwoole 根基入门的具体内容,更多请关注百分百源码网其它相关文章!

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有151人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板