PHP 的redis
擴展是阻塞式 IO ,使用訂閱/發佈模式時,會致使整個進程進入阻塞。所以必須使用Swoole\Redis
異步客戶端來實現。php
$server = new swoole_websocket_server("0.0.0.0", 9501); $server->on('workerStart', function ($server, $workerId) { $client = new swoole_redis; $client->on('message', function (swoole_redis $client, $result) use ($server) { if ($result[0] == 'message') { foreach($server->connections as $fd) { $server->push($fd, $result[1]); } } }); $client->connect('127.0.0.1', 6379, function (swoole_redis $client, $result) { $client->subscribe('msg_0'); }); }); $server->on('open', function ($server, $request) { }); $server->on('message', function (swoole_websocket_server $server, $frame) { $server->push($frame->fd, "hello"); }); $server->on('close', function ($serv, $fd) { }); $server->start();
在進程啓動(onWorkerStart
)時建立了Swoole\Redis
客戶端,鏈接到Redis
服務器web
鏈接成功後,訂閱msg_0
主題的消息redis
當有新的message
時,Swoole\Redis
會觸發onMessage
事件回調服務器
在這個回調函數中使用$server->connections
遍歷服務器全部的鏈接,發送消息websocket