使用workerman實現(xiàn)了websocket服務(wù)端
業(yè)務(wù)中使用了
use Workerman\RedisQueue\Client;
在onClose內(nèi)部關(guān)閉connection
$ws->onClose = function($connection)
{
$connection->close();
unset($connection);
};
但是運行 php demo.php connections時
redis鏈接并沒有被關(guān)閉掉
請教下如何關(guān)閉它們。否則多次鏈接之后,redis進程越來越多了
Workerman\RedisQueue\Client
本身是復(fù)用連接的,不會建立很多連接。Workerman\RedisQueue\Client
目前不支持關(guān)閉,
$ws->onClose = function($connection)
{
$connection->close();
unset($connection);
};
另外這個代碼是關(guān)閉客戶端ws連接,并不是關(guān)閉Workerman\RedisQueue\Client
。unset($connection);
這句沒有必要,$connection
在函數(shù)里是臨時變量,出了函數(shù)作用域自然就釋放了.
“否則多次鏈接之后,redis進程越來越多了”
這個也是錯誤說法,多次連接不會影響進程數(shù),進程和連接是有區(qū)別的。進程數(shù)是固定的,啟動后就不會變動了。
客戶端多次連接,不影響Workerman\RedisQueue\Client
連接數(shù),Workerman\RedisQueue\Client
會復(fù)用連接。開發(fā)過程中不用關(guān)注Workerman\RedisQueue\Client
的連接數(shù)。
Workerman\RedisQueue\Client
一般是放在onWorkerStart進程啟動時初始化的,一個進程只會執(zhí)行一次。不要重復(fù)初始化就行。
請教大佬,如下這樣使用是否正確哦?
$ws->onWorkerStart = function() {
global $asyncRedisQueue;
$asyncRedisQueue = new AsyncRedisQueue('redis://127.0.0.1:6379');
};
$ws->onConnect = function($connection)
{
// WebSocket連接成功
$connection->onWebSocketConnect = function($connection)
{
global $asyncRedisQueue;
// 訂閱并推送消息
$asyncRedisQueue->subscribe('Message:Center:Queue:' . $connection->id, function($info_json) use ($connection) {
$connection->send($info_json);
});
};
};
$ws->onClose = function($connection)
{
$connection->close();
};
謝謝大佬提點,已經(jīng)改正
$ws->onWorkerStart = function() {
global $asyncRedisQueue;
$asyncRedisQueue = new AsyncRedisQueue('redis://127.0.0.1:6379');
};
$ws->onConnect = function($connection)
{
// WebSocket連接成功
$connection->onWebSocketConnect = function($connection)
{
global $asyncRedisQueue;
// 訂閱并推送消息
$asyncRedisQueue->subscribe('Message:Center:Queue:' . $connection->id, function($info_json) use ($connection) {
$connection->send($info_json);
});
};
};
$ws->onClose = function($connection)
{
global $asyncRedisQueue;
// 取消訂閱
$asyncRedisQueue->unsubscribe('Message:Center:Queue:' . $connection->id);
$connection->close();
};