Swoole入门到实战(三):图文直播和聊天室模块、系统监控和性能优化模块、负载均衡 - 完结篇

一、直播、聊天

1.1 图文直播(Redis)

    在线用户处理:
    方案(一):https://wiki.swoole.com/wiki/...(推荐)
    方案(二)redis方案,无序集合Set
    方案(三)swoole-table

    /**
     * 监听ws连接事件
     * @param $ws
     * @param $request
     */
    public function onOpen($ws, $request) {
        // fd redis [1]
        \app\common\lib\redis\Predis::getInstance()->sAdd(config('redis.live_game_key'), $request->fd);
        var_dump($request->fd);
    }

    /**
     * 监听ws消息事件
     * @param $ws
     * @param $frame
     */
    public function onMessage($ws, $frame) {
        echo "ser-push-message:{$frame->data}\n";
        $ws->push($frame->fd, "server-push:".date("Y-m-d H:i:s"));
    }

    /**
     * close
     * @param $ws
     * @param $fd
     */
    public function onClose($ws, $fd) {
        // fd del
        \app\common\lib\redis\Predis::getInstance()->sRem(config('redis.live_game_key'), $fd);
        echo "clientid:{$fd}\n";
    }
// 获取连接的用户
// 赛况的基本信息入库   2、数据组织好 push到直播页面
 $taskData = [
            'method' => 'pushLive',
            'data' => $data
        ];
        $_POST['http_server']->task($taskData);
    /**
     * 通过task机制发送赛况实时数据给客户端
     * @param $data
     * @param $serv swoole server对象
     */
    public function pushLive($data, $serv) {
        $clients = Predis::getInstance()->sMembers(config("redis.live_game_key"));

        foreach($clients as $fd) {
            $serv->push($fd, json_encode($data));
        }
    }
    /**
     * 基础类库优化,优化两个参数的方法(重要)
     * 1.集合的添加和删除
     * @param $name
     * @param $arguments
     * @return array
     */
    public function __call($name, $arguments) {
        //echo $name.PHP_EOL;
        //print_r($arguments);
        if(count($arguments) != 2) {
            return '';
        }
        $this->redis->$name($arguments[0], $arguments[1]);
    }

    Tips:关闭服务后,清除Redis中所有客户端的id

1.2 聊天(connections)

$this->ws = new swoole_websocket_server(self::HOST, self::PORT);
$this->ws->listen(self::HOST, self::CHART_PORT, SWOOLE_SOCK_TCP);
//推荐使用connections这种方式,redis方式也可以
foreach($_POST['http_server']->ports[1]->connections as $fd) {
    $_POST['http_server']->push($fd, json_encode($data));
}

二、系统监控和性能优化模块

2.1 系统监控

/**
 * 监控服务 ws http 9911
 */

class Server {
    const PORT = 9911;
    public function port() {
        $shell  =  "netstat -anp 2>/dev/null | grep ". self::PORT . " | grep LISTEN | wc -l";

        $result = shell_exec($shell);
        if($result != 1) {
            // 发送报警服务 邮件 短信
            /// todo
            echo date("Ymd H:i:s")."error".PHP_EOL;
        } else {
            echo date("Ymd H:i:s")."succss".PHP_EOL;
        }
    }
}

// 每2秒执行一次
swoole_timer_tick(2000, function($timer_id) {
    (new Server())->port();
    echo "time-start".PHP_EOL;
});

    以‘守护进程’方式在后台执行:

nohup /usr/local/php/bin/php /home/wwwroot/swoole/thinkphp/extend/swoole/monitor/server.php > /home/wwwlog/monitor.log &

    检测:

  1. ps aux | grep monitor/server.php
  2. tail -f /home/wwwlog/monitor.log

2.2 平滑重启

/**
 * 设置进程名,为后续平滑重启进程
 * @param $server
 */
public function onStart($server) {
    swoole_set_process_name("live_master");
}        

    reload.sh

echo "loading..."
pid=`pidof live_master`
echo $pid
kill -USR1 $pid
echo "loading success"
# linux 信号控制:USR1 平滑重载所有worker进程并重新载入配置和二进制模块

2.3 nginx 转发到 swoole_server

if (!-e $request_filename ) {
    proxy_pass http://127.0.0.1:9911;
}

三、 负载均衡

负载均衡:nginx必须是单台,其实nginx特别耗费cpu,需要测试nginx的转发量

 代理 - 代为办理(如代理理财、代理收货等等)

3.1 代理分类

    clipboard.png

1、正向代理:

    clipboard.png

2、反向代理:

    clipboard.png

    clipboard.png

3.2 后端服务器在负载均衡调度中的状态

    clipboard.png

模拟downbackup可通过关闭端口: iptables -I INPUT -p tcp --dport 8003 -j DROP
清理规则: iptables -F

3.3 轮询策略

    clipboard.png

ip_hash:解决了不同请求打到不同服务器问题,从而保证了 sessioncookie的一致性。

缺点:客户端可能会再用一层代理**

    url_hash:

    clipboard.png

3.4 负载均衡示例

clipboard.png

完!

猜你喜欢

转载自blog.csdn.net/u010490524/article/details/80476770