0 Star 0 Fork 0

panninan/php_frame

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
swoole.php 2.53 KB
一键复制 编辑 原始数据 按行查看 历史
<?php
use core\request\PhpRequest;
use core\request\RequestInterface;
use core\SwooleContext;
error_reporting(E_ALL);
ini_set('display_errors', 'On');
require_once __DIR__ . '/vendor/autoload.php'; // 引入自动加载
require_once __DIR__ . '/app.php'; // 框架的文件
$start = static function() {
Swoole\Runtime::enableCoroutine($flags = SWOOLE_HOOK_ALL);
// 如果你用了CURL PDO之类的客户端 请开启这个客户端协程化
// 详细见文档: https://wiki.swoole.com/#/runtime
// 绑定主机 端口
$http = new Swoole\Http\Server('0.0.0.0', 9501);
$http->set([
// 进程pid文件
'pid_file' => FRAME_BASE_PATH . '/storage/swoole.pid',
'enable_coroutine' => true, // 开启异步协程化 默认开启
'worker_num' => 4 // Worker进程数 跟协程处理有关系 https://wiki.swoole.com/#/server/setting?id=worker_num
]);
$http->on('request', function($request, $response) {
echo Swoole\Coroutine::getCid() . PHP_EOL; // 打印当前协程id
// 文档:https://wiki.swoole.com/#/coroutine/coroutine?id=getcid
// 绑定request 现在这个是有问题 因为容器的单例的 所以request会一直变(数据错乱)
$server = $request->server;
app()->bind(RequestInterface::class, function() use ($server) {
return PhpRequest::create(
$server['path_info'],
$server['request_method'],
$server
);
});
//使用协程上下文保存当前的request
SwooleContext::put('request', PhpRequest::create(
$server['path_info'],
$server['request_method'],
$server
));
//响应
$response->end(
app('response')->setContent( // 响应
app('router')->dispatch( // 路由
app(RequestInterface::class) // 请求
)
)->getContent()
);
//请求结束删除当前协程变量,以防内存泄漏
SwooleContext::delete();
});
echo 'start ok' . PHP_EOL;
echo 'This Server is listen 0.0.0.0:9501' . PHP_EOL;
$http->start();
};
$stop = static function() {
if (!file_exists(FRAME_BASE_PATH . '/storage/swoole.pid')) {
return;
}
$pid = file_get_contents(FRAME_BASE_PATH . '/storage/swoole.pid');
Swoole\Process::kill($pid); // 见文档
};
$handle = $argv[1];
// 启动
if ('start' === $handle) {
$start();
} elseif ('stop' === $handle) {
$stop();
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
PHP
1
https://gitee.com/PanNinan/php_frame.git
git@gitee.com:PanNinan/php_frame.git
PanNinan
php_frame
php_frame
master

搜索帮助

D67c1975 1850385 1daf7b77 1850385