您好,欢迎访问一九零五行业门户网

EasySwoole 基础入门

使用 composer 安装
composer require easyswoole/easyswoole=3.xphp 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
<?phpnamespace 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 生产配置文件
生命周期,也就是流程
配置文件说明
<?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注入配置
也就是依赖注入
<?phpdi::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 基础入门的详细内容。
其它类似信息

推荐信息