2016-11-11 93 views
0

我運行在集羣模式下的Node.js與socket.io和PM2現在這個樣子(默認socket.io聊天的 「Hello World」 的例子)Socket.io PM2重裝複製插座

var 
    probe = require('pmx').probe(), 
    app = require('express')(), 
    server = require('http').createServer(app), 
    io = require('socket.io')(server), 

    port = 3131 + parseInt(process.env.NODE_APP_INSTANCE), 
    counter = probe.counter({ 
     name: 'User online' 
    }); 



io.on('connection', function(socket) { 
    counter.inc(); 
    socket.on('disconnect', function() { 
     counter.dec(); 
    }); 

    socket.on('message', function() { 
     socket.emit('message', port); 
    }); 
}); 

server.listen(port, function() {}); 

和默認的HTML客戶端(所有誰訪問我的網頁,將執行此)

var socket; 
window.addEventListener("load", function() { 
    socket = io.connect('http://localhost:3000/', { 
     'reconnection': true, 
     'reconnectionDelay': 500, 
     'reconnectionAttempts': 3 
    }); 

    socket.on('message', function(message) { 
     console.log(message); 
    }); 

    setInterval(function() { 
     socket.emit('message', {}); 
    }, 2000); 
}); 

這正好與默認nginx的粘性會話配置(http://socket.io/docs/using-multiple-nodes/發現這裏的一個區別,我跳過了最後Redis的部分,只使用nginx的配置)

upstream io_nodes { 
    ip_hash; 
    server 127.0 .0 .1: 3131; 
    server 127.0 .0 .1: 3132; 
    server 127.0 .0 .1: 3133; 
    server 127.0 .0 .1: 3134; 
    server 127.0 .0 .1: 3135; 
    server 127.0 .0 .1: 3136; 
    server 127.0 .0 .1: 3137; 
    server 127.0 .0 .1: 3138; 
} 

和PM2的配置是這樣的:

{ 
    "apps": [{ 
     "name": "server", 
     "script": "server.js", 
     "instances": 8, 
     "exec_mode": "cluster", 
     "max_memory_restart": "2G" 
    }] 
} 

,我有幾個問題:

  1. 首先是用戶在線數爲李建華,伍妍全當我的項目,在線用戶數,例如(實案例!)如果我有3800個用戶在線,我的keymetrics(或簡單的io.eio.clientsCount)顯示4000或甚至5000個連接的總客戶端。從第一個,如果我使用pm2重新加載或pm2重新啓動,我有情況下,當第一個節點重複或甚至乘以幾次套接字計數,並獲得100%+ cpu負載。有時候,所有的節點,不僅是首先乘以套接字數量。爲了避免這種情況,我需要殺死pm2,等一下,然後再次開始。

PM2重裝後狀況(實際存在網上只有3868用戶):

in real there is only 3868 users online

+0

對於你的第一個問題,'socket.io'向服務器發出一次以上的請求。因此,「Keymetrics」可能會顯示更多的計數。我建議與他們分享這個問題。我想知道你的第二個問題的解決方案。 – efkan

+0

可能的解決方案(的想法)https://github.com/Unitech/pm2/issues/2508#issuecomment-259962370 – MyMomSaysIamSpecial

回答

0

,如果你不介意的話只用一個進程來處理WS, 你可以這樣做:

let clusterId = process.env.NODE_APP_INSTANCE 
if (clusterId > 0) return app 
//otherwise, do atttch the ws server 
+0

謝謝,已通過JWT通過身份驗證解決,現在一切都很好:) – MyMomSaysIamSpecial