我是“服务器端 JS”的新手,找不到使用 Node.js 和 Redis-Sub 进行长轮询的示例。
以下代码运行良好,但今天我注意到 RAM 使用量为 650MB,并且代码只运行了 6 天。
var http = require('http'),
redis = require('redis'),
client = redis.createClient();
client.subscribe("example");
http.createServer(function (req, res) {
res.setHeader('Access-Control-Allow-Origin', 'https://mywebsite.com');
res.setHeader('Access-Control-Allow-Methods', 'GET');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
res.writeHead(200, {'Content-Type': 'application/json'});
client.on("message", function (channel, message) {
res.end( JSON.stringify( message ) );
});
}).listen(8080);
有人可以指出内存泄漏并解释一下吗?
我的node.js版本是:v0.10.21
最佳答案
“内存泄漏”来自代码client.on
。您可以在请求/响应函数中调用它。 client.on
是一个发射器(请参阅 redis 源代码,index.js:111(截至今天的 npm 安装)),它定义了函数 on
Adds a listener to the end of the listeners array for the specified event. (Nodejs-Docs: 1)
因此,您不断向客户端添加“消息”
功能。将 client.on
移到此请求/响应“循环”之外,它应该会停止“泄漏”。
关于Node.js redis 订阅内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21055656/