前言
本文主要給大家介紹了關于Yii2結合Workerman的websocket的相關內容,兩者都是好東西,我就想著能不能結合起來,這樣Yii2出現瓶頸的時候有些業務就可以平滑地遷移到Workerman中。下面話不多說了,來隨著小編來一起看看詳細的介紹吧
步驟如下
1、安裝workerman
composer require workerman/workerman
2、啟動workerman
創建commands/WorkermanWebSocketController.php文件
創建actionIndex()函數,用來啟動,代碼如下
public function actionIndex(){ if ('start' == $this->send) { try { $this->start($this->daemon); } catch (/Exception $e) { $this->stderr($e->getMessage() . "/n", Console::FG_RED); } } else if ('stop' == $this->send) { $this->stop(); } else if ('restart' == $this->send) { $this->restart(); } else if ('reload' == $this->send) { $this->reload(); } else if ('status' == $this->send) { $this->status(); } else if ('connections' == $this->send) { $this->connections(); }}
添加初始化模塊
public function initWorker(){ $ip = isset($this->config['ip']) ? $this->config['ip'] : $this->ip; $port = isset($this->config['port']) ? $this->config['port'] : $this->port; $wsWorker = new Worker("websocket://{$ip}:{$port}"); // 4 processes $wsWorker->count = 4; // Emitted when new connection come $wsWorker->onConnect = function ($connection) { echo "New connection/n"; }; // Emitted when data received $wsWorker->onMessage = function ($connection, $data) { // Send hello $data $connection->send('hello ' . $data); }; // Emitted when connection closed $wsWorker->onClose = function ($connection) { echo "Connection closed/n"; };}
添加啟動模塊
/** * workman websocket start */public function start(){ $this->initWorker(); // 重置參數以匹配Worker global $argv; $argv[0] = $argv[1]; $argv[1] = 'start'; if ($this->daemon) { $argv[2] = '-d'; } // Run worker Worker::runAll();}
添加停止模塊
/** * workman websocket stop */public function stop(){ $this->initWorker(); // 重置參數以匹配Worker global $argv; $argv[0] = $argv[1]; $argv[1] = 'stop'; if ($this->gracefully) { $argv[2] = '-g'; } // Run worker Worker::runAll();}
添加重啟模塊
/** * workman websocket restart */public function restart(){ $this->initWorker(); // 重置參數以匹配Worker global $argv; $argv[0] = $argv[1]; $argv[1] = 'restart'; if ($this->daemon) { $argv[2] = '-d'; } if ($this->gracefully) { $argv[2] = '-g'; } // Run worker Worker::runAll();}
添加重載模塊
新聞熱點
疑難解答
圖片精選