Reputation: 5975
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?
Upvotes: 0
Views: 1100
Reputation: 2792
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.
Upvotes: 0
Reputation: 197
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.
Upvotes: 1