简体   繁体   English

可能有node.js redis后备吗?

[英]Possible to have node.js redis fallback?

In Laravel, you can do something like 在Laravel中,您可以执行以下操作

$object = Cache->remember(key, duration, function() {
 $result = mysql_fetch_something();// retrieve from MySQL here
 return $result;
 });

where basically, Laravel checks the cache first if it exists there, and if not, it allows you to retrieve the value from the database and automatically put it in cache while also returning it. 从根本上讲,Laravel首先检查缓存是否存在,如果不存在,它允许您从数据库中检索值并将其自动放入缓存中,同时还返回它。 Is there a similar construct in node; 节点中是否有类似的构造? that is, a 1 stop cache check, db failover mechanism? 也就是说,1停止缓存检查,数据库故障转移机制?

In node there is no special command for this but you can build it yourself. 在节点中,没有特殊的命令,但是您可以自己构建。

Just check with the redis command EXISTS whether the key is in redis and if not just check mysql and store it. 只需使用redis命令EXISTS检查密钥是否在redis中,如果不是,则仅检查mysql并将其存储。

You can do some thing like this. 您可以做这样的事情。 in cache.js cache.js

var isCacheAvailable = true;

exports.init = function () {

    var server = config.get('Cache.server');
    var port = config.get('Cache.port');
    client = redis.createClient(port,server);

    // handle redis connection temporarily going down without app crashing
    client.on("error", function (err) {
        logger.error("Error connecting to redis server " + server + ":" + port, err);
        isCacheAvailable = false;
    });

}

exports.isCacheAvailable = function(){
    return isCacheAvailable;
}

Check the isCacheAvailable() function where you intend to use cache. 检查打算在其中使用缓存的isCacheAvailable()函数。

if(cache.isCacheAvailable()) { 
    // use cache to fetch data
} else {
   // fallback to mysql db
}

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM