使用SailsJS/Express在请求之间将对象保留在内存中 [英] Keep Object In Memory Between Requests with SailsJS/ Express

查看:74
本文介绍了使用SailsJS/Express在请求之间将对象保留在内存中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 SailsJS (在Express之上构建的框架)构建服务器,并且需要在两次请求之间将对象保留在内存中.我想这样做是因为将它加载到数据库中或从数据库中加载花费的时间太长了.有什么想法可以做到吗?

I'm building a server using SailsJS (a framework built on top of Express) and I need to keep an object in memory between requests. I would like to do this because loading it to/ from a database is taking way too long. Any ideas how I could do this?

这是我的代码:

var params = req.params.all();

Network.findOne({ id: params.id }, function(err, network) {
  if(network) {
    var synapticNetwork = synaptic.Network.fromJSON(network.jsonValue);
    if(synapticNetwork) { ...

具体地说,fromJSON()函数花费的时间太长了,我宁愿在服务器运行时将synapticNetwork对象保留在内存中(也就是在服务器启动时加载它,并定期保存).

Specifically, the fromJSON() function takes way too long and I would rather keep the synapticNetwork object in memory while the server is running (aka. load it when the server starts and just save periodically).

推荐答案

有很多用于缓存的库,其中之一是 node-cache .它们都共享相似的api:

There are plenty libraries out there for caching purposes, one of which is node-cache as you've mentioned. All of them share similar api :

var cache = require('memory-cache');

// now just use the cache

cache.put('foo', 'bar');
console.log(cache.get('foo'))

您还可以实现自己的模块,并在任何需要的地方使用它:

You can also implement your own module and just require it wherever you need:

var cache = {};

module.exports = {
    put: function(key, item) {
        cache[key] = item;
    },
    get: function(key) {
        return cache[key];
    }
}

这篇关于使用SailsJS/Express在请求之间将对象保留在内存中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆