基于swoole搭建的一个高性能的HTTP服务器
├── README.md
├── bin
│ ├── Client.php
│ ├── Command.php
│ ├── HttpServer.php
│ ├── Log.php
│ ├── Route.php
│ ├── ServerQueue.php
│ ├── controller
│ │ ├── Controller.php
│ │ ├── IndexController.php
│ │ └── Response.php
│ ├── exception
│ │ └── HttpException.php
│ ├── pool
│ │ ├── DB.php
│ │ ├── DbPool.php
│ │ ├── Pool.php
│ │ ├── Mysqli.php
│ │ ├── PDO.php
│ │ └── RedisPool.php
│ ├── queue
│ │ └── Queue.php
│ ├── static
│ │ └── favicon.ico
│ └── utility
├── composer.json
├── composer.lock
├── config
│ ├── database.php
│ ├── email.php
│ ├── log.php
│ ├── route.php
│ └── server.php
├── docs
├── helpers.php
├── http.php
├── tcp.php
├── test
├── tests.php
└── view
├── 404.html
├── echarts.html
└── log_list.html- 使用大量单例 避免使用
static属性 PHP全局变量产生内存泄漏问题 - 支持简单的路由分发\控制 简洁的控制器
- 支持redis、mysql连接池 实现了curd 以及事务操作
- php版本>=7.3
- swoole4
get clone https://github.com/pl1998/swoole_http.git
php http.php
全局辅助函数文件
helpers.php 通过composer.json文件 中autoload` 实现了自动加载 主要实现一些全局函数 读取视图函数 view() 读取配置函数 config()
...
"autoload": {
"psr-4": {
"app\\": "bin" //主目录自动加载 映射命名空间
},
"files": [
"helpers.php"
]
}
...├── config
│ ├── database.php //数据库配置
│ ├── route.php //路由文件
│ └── server.php //tcp http 配置以及端口/**
* 路由配置
*/
return [
'GET' => [
'/favicon.ico'=>false,
//访问路径 => 实例控制器 方法名
'/api/tests'=>[\app\controller\TestController::init(),'tests'],
],
'POST' => [
],
'PUT' => [
],
'DELETE' => [
]
];namespace app\controller;
use app\pool\DbPool;
class TestController
{
//每个控制器都应该有的单例
protected static $init;
public static function init()
{
if(is_null(static::$init)) {
echo "加载控制器单例"."\n";
static::$init = new self();
}
return static::$init;
}
//拿到请求和响应
public function test(object $request,object $response)
{
//业务逻辑
$db = new DbPool();
$id = $db->table('users')->insert([
'name'=>'latent',
'password'=>'',
'avatar'=>'',
'email'=>'[email protected]',
'created_at'=>date('Y-m-d H:i:s'),
'updated_at'=>date('Y-m-d H:i:s'),
'uid'=>'56895',
'age'=>22,
]);
$response->header('Content-Type','application/json');
$response->end(success([
'id'=>$id
],'插入成功'));
}
}php http.php
---------------
$ php http.php
0.0.0.0:9501 public function test(object $request,object $response)
{
$response->header('Content-Type', 'text/html');
$response->end("hello world!");
}浏览器访问0.0.0.0:9501 尝试多请求几次
####命令行
$ php http.php
0.0.0.0:9501
当前使用内存:1489312
加载路由单例
加载Index控制器单例
加载Test控制器单例
当前使用内存:1584304
当前使用内存:1584304
当前使用内存:1584304
当前使用内存:1584304
当前使用内存:1584304
当前使用内存:1584304
当前使用内存:1584304wrk -t4 -c50 -d30 http://127.0.0.1:9501/api/testreturn [
'mysql' =>[
'host'=>'127.0.0.1',
'port'=>3306,
'coding'=>'utf8mb4',
'dbname'=>'swoole',
'username'=>'root',
'password'=>'root',
'size'=>15, //默认只给连接池15个连接
]
];
Latency参数明显高一点了 但Requests/sec只提高了40个的样子 如果用协程来跑性能应该更高





