Socket.io节点服务器使用高CPU

时间:2011-12-31 09:44:42

标签: node.js socket.io

我的套接字服务器工作正常3-4天,但在数据之后,我收到来自Munin的通知,它超出了指定的CPU范围(160)。听起来像记忆不是免费的:d正确,但我找不到哪里?

var io = require('socket.io').listen(80);
var Memcached = require('memcached');
var md5 = require('MD5');
var memcached = new Memcached(['IP']);
var interval_time = 5000;

loglevel = process.argv[2];
if(loglevel == "") loglevel = 1;

io.enable('browser client minification');  // send minified client
io.enable('browser client etag');          // apply etag caching logic based on version number
io.enable('browser client gzip');          // gzip the file

io.sockets.on('connection', function (socket)
{
     socket.on('get_notifications', function (data)
     {
         // verify authorization
        if(data.key == 'XXXXXXX')
        {
            socket.user_id = data.user_id;

            setInterval(function()
            { 
                memcached.get(["ntf_" + socket.user_id, "nnt_" + socket.user_id], function(error, mem_result)
                {
                    num_orders = mem_result['ntf_' + socket.user_id];
                    is_searching = mem_result['nnt_' + socket.user_id];

                    if(typeof(socket.prev_notification)==='undefined') socket.prev_notification = {};

                    var notification = socket.prev_notification;
                    var have_new_notifications = false;

                    if(is_searching != socket.prev_notification.nnt)
                    {
                        have_new_notifications = true;
                        notification.nnt = is_searching;
                    }

                    if(num_orders != socket.prev_notification.ntf)
                    {
                        have_new_notifications = true;
                        notification.ntf = num_orders;
                    }

                    if(have_new_notifications)
                    {
                        var today=new Date();
                        var h=today.getHours();
                        var m=today.getMinutes();
                        var s=today.getSeconds();

                        console.log(h+":"+m+":"+s+' - sending notification to ' + data.user_id);
                        console.log(notification);

                        socket.emit('notifications', notification);
                        socket.prev_notification = notification;
                    }
                });
            }, interval_time); // interval
        }
    });
});

1 个答案:

答案 0 :(得分:2)

我认为问题在于每次setInterval事件被触发时都会触发get_notification。这些间隔一旦开始就永远不会停止工作。

您应该编写一些代码,以便在满足某些条件时停止这些间隔(超时?客户端断开连接等等)。或者将setInterval更改为setTimeout,除非抛出异常(例如无法将数据发送到断开连接的客户端),否则它将自动触发。