1. 服务监控;
- 创建监控文件
server/script/monitor/server.php
<?php
class Server{
const PORT = 8811;
public function port(){
$shell = "netstat -anp 2>/dev/null | grep " . self::PORT . " | grep LISTEN | wc -l";
$result = shell_exec($shell);
if($result != 1) {
echo date("Y-m-d H:i:s")." - error".PHP_EOL;
} else {
echo date("Y-m-d H:i:s")." - success".PHP_EOL;
}
}
}
swoole_timer_tick(2000, function($timer_id) {
(new Server())->port();
});
nohup php server.php > /data/project/test/swoole/tp5/server/script/monitor/a.txt &
[1] 31898
ps -ef | grep server.php
tail -f a.txt
kill 31898
2. 多个请求过滤;
<?php
if($request->server['request_uri'] == '/favicon.ico'){
$response->status(404);
$response->end();
return;
}
3. 服务平滑重启;
-
常见信号源:
-
sigterm:停止服务器
-
sigusr1:平滑重启 worker 进程
-
sigusr2:全部重启 task worker 进程
$this->ws->on("start", [$this, 'onStart']);
public function onStart($server){
swoole_set_process_name('live_master');
}
#! /bin/bash
echo "loading..."
pid=`pidof live_master`
echo $pid
kill -USR1 $pid
echo "loading success"
sh reload.sh
nohup php ws.php > /data/project/test/swoole/tp5/server/script/monitor/ws.log &
4. 负载均衡概述;
-
项目架构:
-
如上图 1,用户来访问的时候,首先通过域名走到 Swoole HttpServer。PHP 和一些静态文件(HTML 页面,图片文件等)都是通过 Swoole 设置的。但是实际工作的时候这种架构是不建议的。
-
可以用 Swoole HttpServer 去做应用层的内容,上层最好去加一个 Nginx 服务器做负载均衡。像系统中的一些静态资源,放到 Nginx 里是非常合适的,因为 Nginx 可以有很多设置,比如设置静态资源的缓存时间,可以提升性能。还可以从 Nginx 里做一个转发,把用户请求的应用层的东西转发,转发到 Swoole HttpServer 里。
-
如上图 2,用户通过域名访问的时候,先是走到 Nginx,如果 Nginx 里有静态资源,就直接返回给用户。如果没有静态资源,Nginx 就转发内容到 Swoole HttpServer 里去, 通过 Swoole HttpServer 应用层的 PHP 脚本去处理业务,最终把数据返回给 Nginx,Nginx 返回给用户。这样做,就可以在 Nginx 这里做代理服务器,性能就比较好一点。
-
如上图 3,可以做负载均衡。项目里不可能用一台 Swoole HttpServer,一般都是分布式多台。
-
如下图,现在做分布式,机器肯定是遍布全国甚至全球。把集群拆分成北方和南方等等。用户访问网站遵循就近原则找到最近的集群。
5. Nginx 静态文件支持、转发到 Swoole 服务器;
-
相关配置:
-
添加 Nginx 配置文件如下:
/usr/local/nginx/conf/conf.d/tp5.conf
-
重启 Nginx:
../../sbin/nginx -s reload
server {
listen 8823;
server_name localhost;
location / {
root /data/project/test/swoole/tp5/public/static/;
index index.php index.html;
if (!-e $request_filename ) {
proxy_pass http://127.0.0.1:8811;
}
}
}
-
配置后:
-
重启后可通过 Nginx 的 8823 端口访问静态页面:
http://192.168.2.214:8823/live/login.html
-
8823 端口因为没有配置 php-fpm 所以不能直接访问 PHP 页面。添加
转发到 Swoole 服务器 相关配置后,访问
http://192.168.2.214:8823/index/index/hualaoshuan 可以访问到 PHP 内容。解释:用户的请求先到 Nginx,然后 Nginx 再做一个转发到 Swoole 服务器,访问到了 PHP 内容
6. 负载均衡。
- Swoole 机器有多台的时候,如何通过 Nginx 去做负载均衡
- 修改 :
/usr/local/nginx/conf/conf.d/tp5.conf
upstream swoole_http {
server 127.0.0.1:8811 weight=2;
server 127.0.0.1 weight=1;
}
server {
listen 8823;
server_name localhost;
location / {
root /data/project/test/swoole/tp5/public/static/;
index index.php index.html;
if (!-e $request_filename ) {
proxy_pass http://swoole_http;
}
}
}
-
注意:
-
Nginx 机器必须是单台独立的去做转发。
-
Nginx 做转发是很耗 CPU 的,需要测试转发量。