简体   繁体   中英

Possible to have node.js redis fallback?

In Laravel, you can do something like

$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. Is there a similar construct in node; that is, a 1 stop cache check, db failover mechanism?

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.

You can do some thing like this. in 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.

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

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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