一、Swoole 安装
下载源码编译安装( pecl install swoole安装易失败):
#下载源码
git clone https://github.com/swoole/swoole-src.git
#如果clone不下来可以选择: git clone ttps://gitee.com/swoole/swoole.git
#进入源码目录并选择最新tag
cd swoole-src
git checkout v4.3.3
#或 cd swoole
#git checkout v4.3.2
phpize
./configure --with-php-config=/usr/local/php/bin/php-config
make && make install
#配置php.ini 添加:
extension=swoole.so
#执行php -m 查看拓展是否安装成功
二、Swoole 搭建Http服务器
1、简单服务搭建
<?php
//(1)创建swool的http服务器对象
$serv = new swoole_http_server('0.0.0.0',8000);
//(2)当浏览器链接点这个http服务器的时候,向浏览器发送helloworld
$serv->on('request',function($request,$response){
//(2.1)$request包含这个请求的所有信息,比如参数
//(2.2)$response包含返回给浏览器的所有信息,比如helloworld
var_dump($request);
var_dump($response);
//(2.3)向浏览器发送helloworld
$response->end("hello world");
});
//(3)启动http服务器
$serv->start();
?>
#执行测试
php sw_http.php
curl http://127.0.0.1:8000
2、原理解析
启动swoole的时候会启动Manager进程和Master进程。对于Manager进程,用于管理Worker进程(我们业务层的逻辑代码一般放在这里)和Task进程(用于在某个特定的时间或者条件下执行的代码)。对于Master进程,用于底层的开发,后面详细介绍.如下图:
1. 在这个swoole服务器启动后,会创建三个进程
* Manager
* Worker
* Task
2.这个Manager进程是Worker进程的守护进程,在这个Worker进程意外结束后,这个Manager进程会重新启动Workder进程,Manager进程只有一个,而这个Worker可以有多个。
3.Worker进程通过给这个Task进程发送任务,可以把一些计算量大的任务转移到Task进程,这样我们的Worker进程就可以高速处理客户端的请求,提高并发量。
4.reactor线程是swoole底层处理高并发,最大限度的调用底层资源。
3、简单的swoole http 服务器实例
<?php
/**
* 简单的swoole http 服务器实例
* User: guola
* Date: 2019/5/10
* Time: 18:12
*/
use Swoole\Http\Server as http_server;
$setting = [
'reactor_num' => 1,
'worker_num' => 2,
'max_request' => 1000,
'task_worker_num' => 1,
'task_tmpdir' => '/tmp',
'daemonize' => 0,
'log_file' => __DIR__.'/swlog.txt',
'pid_file' => __DIR__.'/swhttpserver.pid',
];
function startSwHttpServer($setting){
$webserver = new http_server('0.0.0.0', '8881', SWOOLE_PROCESS, SWOOLE_SOCK_TCP);//如果ssl SWOOLE_SOCK_TCP | SWOOLE_SSL
$webserver->set($setting);
/**
* start回调
*/
$webserver->on('Start', function(http_server $server) {
echo 'Start...',"\n";
// 重新设置进程名称
swoole_set_process_name('swhttp-master');
});
/**
* managerstart回调
*/
$webserver->on('ManagerStart', function(http_server $server) {
echo 'manager start...',"\n";
// 重新设置进程名称
swoole_set_process_name('swhttp-manager');
});
/**
* managerstop回调
*/
$webserver->on('ManagerStop', function(http_server $server) {
echo 'manager stop...',"\n";
});
/**
* 启动worker进程监听回调,设置定时器
*/
$webserver->on('WorkerStart', function(http_server $server, $worker_id) use($setting) {
// 设置worker的进程
if($worker_id >= $setting['worker_num']) {
swoole_set_process_name("swhttp-task".$worker_id);
}else {
swoole_set_process_name("swhttp-worker".$worker_id);
}
// 延迟绑定
onWorkerStart($server, $worker_id);
});
/**
* worker进程停止回调函数
*/
$webserver->on('WorkerStop', function(http_server $server, $worker_id) {
echo 'worker stop...',"\n";
});
/**
* 接受http请求
*/
$webserver->on('request', function(Request $request, Response $response) {
try{
onRequest($request, $response);
return true;
}catch(\Exception $e) {
echo $e;
}
});
$webserver->on('task', function(http_server $server, $task_id, $from_worker_id, $data) {
try{
$task_data = unserialize($data);
onTask($server, $task_id, $from_worker_id, $task_data);
}catch(\Exception $e) {
echo $e;
}
});
$webserver->start();
}
//请求处理即传统web/MVC框架启动处
function onRequest($request, $response){
echo 'onRequest...',"\n";
}
function onWorkerStart($server, $worker_id){
echo 'onWorkerStart...',"\n";
}
function onTask($server, $task_id, $from_worker_id, $task_data){
echo 'onTask...',"\n";
}
startSwHttpServer($setting);
//在onRequest方法中启动执行MVC框架
4、接入Slim框架
1、composer create-project slim/slim-skeleton ss
2、cd ss
3、创建脚本SlimSwooleHttpServier.php 脚本如下:
<?php
use Slim\Http\Environment;
class SlimSwooleHttpServier{
public $host='0.0.0.0';
public $port=6666;
public $http="";
public function __construct()
{
$this->http = new Swoole\Http\Server($this->host, $this->port);
$this->http->set([
//'daemonize'=>1,
'worker_num'=>4
]);
$this->http->on('Start',[$this,'MasterStart']);
$this->http->on('ManagerStart',[$this,'ManagerStart']);
$this->http->on('WorkerStart',[$this,'WorkerStart']);
$this->http->on('request',[$this,'request']);
$this->http->start();
}
public function MasterStart(){
swoole_set_process_name('sshttp-master');
}
public function ManagerStart(){
swoole_set_process_name('sshttp-manager');
}
public function WorkerStart($server,$worker_id){
define("ROOT",__DIR__);
define('APP', ROOT . '/src');
swoole_set_process_name('sshttp-worker');
require ROOT . '/vendor/autoload.php';
echo $worker_id."\n";
}
public function request($request,$response){
$config = require APP . '/settings.php';
$config['environment'] = function () use($request) {
$_SERVER = [];
foreach ($request->server as $key => $value) {
$_SERVER[strtoupper($key)] = $value;
}
return new Environment($_SERVER);
};
$_GET=[];
if(isset($request->get)){
$_GET = $request->get;
}
$_POST=[];
if(isset($request->post)){
$_POST = $request->post;
}
$app = new \Slim\App($config);
require APP . '/dependencies.php';
require APP . '/routes.php';
// Register middleware
$middleware = require APP . '/middleware.php';
$middleware($app);
// Register routes
$routes = require APP . '/routes.php';
$routes($app);
// Run app
$slimResponse = $app->run(true);
$headers = $slimResponse->getHeaders();
foreach ($headers as $name => $values) {
$response->header($name, implode(", ", $values));
}
$response->header("X-Powered-By", "Salamander");
$response->end($slimResponse->getBody());
}
}
new SlimSwooleHttpServier();
?>
4、添加路由:vim src/routes.php 添加路由:
$app->get('/hello/{name}', function (Request $request, Response $response, array $args) {
$name = $args['name'];
$response->getBody()->write("Hello, $name\n");
return $response;
});
5、执行php SlimSwooleHttpServier.php
6、测试:curl -i http://127.0.0.1:6666/hello/123
HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
X-Powered-By: Salamander
Server: swoole-http-server
Connection: keep-alive
Date: Tue, 21 May 2019 01:31:46 GMT
Content-Length: 10
Hello, 123