workerman 服務

丶XianGang發表於2024-04-07
# 透過 composer 安裝 workerman
"workerman/workerman": "^4.1",
"workerman/gatewayclient": "^3.0",
"workerman/gateway-worker": "^3.1",

# api 新建檔案 workerman  放 Events.php ,start_businessworker.php ,start_gateway.php,start_register.php 檔案

Events.php
<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */
/**
 * 用於檢測業務程式碼死迴圈或者長時間阻塞等問題
 * 如果發現業務卡死,可以將下面declare開啟(去掉//註釋),並執行php start.php reload
 * 然後觀察一段時間workerman.log看是否有process_timeout異常
 */
//declare(ticks=1);

use \GatewayWorker\Lib\Gateway;

/**
 * 主邏輯
 * 主要是處理 onConnect onMessage onClose 三個方法
 * onConnect 和 onClose 如果不需要可以不用實現並刪除
 */
class Events
{
    /**
     * 當客戶端連線時觸發
     * 如果業務不需此回撥可以刪除onConnect
     * 
     * @param int $client_id 連線id
     */
    public static function onConnect($client_id)
    {
        // 向當前client_id傳送資料 
        Gateway::sendToClient($client_id, json_encode(array(
            'client_id' => $client_id
        )));
        // 向所有人傳送
        //Gateway::sendToAll("$client_id 風起時");
    }
    
   /**
    * 當客戶端發來訊息時觸發
    * @param int $client_id 連線id
    * @param mixed $message 具體訊息
    */
   public static function onMessage($client_id, $message)
   {
        // 向所有人傳送 
        //Gateway::sendToAll("$client_id said $message\r\n");
       //echo $message;
   }
   
   /**
    * 當使用者斷開連線時觸發
    * @param int $client_id 連線id
    */
   public static function onClose($client_id)
   {
       // 向所有人傳送 
       //GateWay::sendToAll("$client_id logout\r\n");
   }

    // 程序啟動時設定個定時器。Events中支援onWorkerStart需要Gateway版本>=2.0.4
    /*public static function onWorkerStart()
    {
        \Workerman\Timer::add(1, function(){
            echo "fengqishi\n";
            \app\common\model\CharteredBusCancelCause::create(['cause' => rand(100, 999)]);
        });
    }*/
}

tart_businessworker.php

<?php 
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */
use \Workerman\Worker;
use \Workerman\WebServer;
use \GatewayWorker\Gateway;
use \GatewayWorker\BusinessWorker;
use \Workerman\Autoloader;

// 自動載入類
require_once __DIR__ . '/../../../vendor/autoload.php';
require_once __DIR__ . '/Events.php';
// bussinessWorker 程序
$worker = new BusinessWorker();
// worker名稱
$worker->name = 'landian';
// bussinessWorker程序數量
$worker->count = 1;
// 服務註冊地址
$worker->registerAddress = '127.0.0.1:1241';
$worker->eventHandler = "Events";

// 如果不是在根目錄啟動,則執行runAll方法
if(!defined('GLOBAL_START'))
{
    Worker::runAll();
}

start_gateway.php

<?php 
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */
use \Workerman\Worker;
use \Workerman\WebServer;
use \GatewayWorker\Gateway;
use \GatewayWorker\BusinessWorker;
use \Workerman\Autoloader;

// 自動載入類
require_once __DIR__ . '/../../../vendor/autoload.php';

// gateway 程序,這裡使用Text協議,可以用telnet測試
$gateway = new Gateway("websocket://0.0.0.0:8288");
// gateway名稱,status方便檢視
$gateway->name = 'landian';
// gateway程序數
$gateway->count = 4;
// 本機ip,分散式部署時使用內網ip
$gateway->lanIp = '127.0.0.1';
// 內部通訊起始埠,假如$gateway->count=4,起始埠為4000
// 則一般會使用4000 4001 4002 4003 4個埠作為內部通訊埠 
$gateway->startPort = 4004;
// 服務註冊地址1236
$gateway->registerAddress = '127.0.0.1:1241';

// 心跳間隔
$gateway->pingInterval = 10;
// 心跳資料
$gateway->pingData = '{"type":"ping"}';

/* 
// 當客戶端連線上來時,設定連線的onWebSocketConnect,即在websocket握手時的回撥
$gateway->onConnect = function($connection)
{
    $connection->onWebSocketConnect = function($connection , $http_header)
    {
        // 可以在這裡判斷連線來源是否合法,不合法就關掉連線
        // $_SERVER['HTTP_ORIGIN']標識來自哪個站點的頁面發起的websocket連結
        if($_SERVER['HTTP_ORIGIN'] != 'http://kedou.workerman.net')
        {
            $connection->close();
        }
        // onWebSocketConnect 裡面$_GET $_SERVER是可用的
        // var_dump($_GET, $_SERVER);
    };
}; 
*/

// 如果不是在根目錄啟動,則執行runAll方法
if(!defined('GLOBAL_START'))
{
    Worker::runAll();
}

  start_register.php

<?php 
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */
use \Workerman\Worker;
use \GatewayWorker\Register;

// 自動載入類
require_once __DIR__ . '/../../../vendor/autoload.php';

// register 必須是text協議
$register = new Register('text://0.0.0.0:1241');

// 如果不是在根目錄啟動,則執行runAll方法
if(!defined('GLOBAL_START'))
{
    Worker::runAll();
}

 # 根目錄下新建 start.php

<?php
/**
 * run with command
 * php start.php start
 */

ini_set('display_errors', 'on');
use Workerman\Worker;

if(strpos(strtolower(PHP_OS), 'win') === 0)
{
    exit("start.php not support windows, please use start_for_win.bat\n");
}

// 檢查擴充套件
if(!extension_loaded('pcntl'))
{
    exit("Please install pcntl extension. See http://doc3.workerman.net/appendices/install-extension.html\n");
}

if(!extension_loaded('posix'))
{
    exit("Please install posix extension. See http://doc3.workerman.net/appendices/install-extension.html\n");
}

// 標記是全域性啟動
define('GLOBAL_START', 1);
define('DS', DIRECTORY_SEPARATOR);
define('ROOT_PATH', __DIR__ . DS);
require_once __DIR__ . '/vendor/autoload.php';

// 載入所有Applications/*/start.php,以便啟動所有服務
foreach(glob(__DIR__.'/application/api/fengqishi/start*.php') as $start_file)
{
    require_once $start_file;
}
// 執行所有服務
Worker::runAll();

啟動 workerman 服務 php start.php start
停止 workerman 服務 php start.php stop
重啟 workerman 服務 php start.php restart
Workerman服務狀態 php start.php status

# 前段連線 workerman 在偽靜態設定
location /wss {
proxy_pass http://127.0.0.1:8288;
proxy_connect_timeout 30s;
proxy_read_timeout 86400s;
proxy_send_timeout 30s;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
}

注意:workerman 埠 8288 和 1241 ;composer包gateway-worker檔案和gatewayclient檔案也需要同步修改 1241 埠
# composer包 預設埠號 1236

啟動成功後
# 繫結操作
public function bindClientId()
{
  #client_id 前段傳引數
  $client_id = $this->request->post('client_id', '');
  $user_id = ""; //使用者ID
  if (!empty($client_id)){
  Gateway::bindUid($client_id, $user_id);
  }
  $this->success();
}
# 推送操作
public function demo(){
  $user_id = ""; //使用者ID
  Gateway::sendToUid($user_id,json_encode([
    'type' => 'order', //型別前段接受
  ]));
}

相關文章