Nodejs内存存储

18 storage node.js

如何存储要用于服务器中所有客户端的数据?(比如聊天的消息)

Ion*_*tan 22

node.js允许您构建的服务器是应用程序服务器,这意味着在请求之间,在服务器端保留状态.以下代码段演示了这一点:

var sys  = require('sys'),
    http = require('http');

var number = 0;

http.createServer(function (req, res) {
        console.log(req.method, req.url);

        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write('<h1>Number is: ' + number + '</h1>');
        res.end();

        number++;

}).listen(8000);

sys.puts('Server running at http://127.0.0.1:8000/');
Run Code Online (Sandbox Code Playgroud)

  • @Thomas David Baker,是的,浏览器对favicon.ico做了额外的请求.我已经修改了代码片段以支持最新版本的节点并在控制台中记录请求方法和URL.现在看看.它应该在每个其他请求之间显示类似`GET/favicon.ico`的内容. (9认同)
  • 在集群中运行您的应用程序时,请谨慎使用此示例。由于应用程序变量是您应用程序的本地变量,因此您无法跨应用程序集群维护状态。 (3认同)

iaj*_*jnr 8

node-cache包是目前最好的键值存储,它允许同步和异步存储/检索/删除键。

npm 链接


Bha*_*ani 5

如果您想要更多功能,请查看redis-node-client