-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Cache: Implementing redis cache on common services
- Loading branch information
1 parent
c43d1d0
commit e58e8c5
Showing
2 changed files
with
59 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
var redis = require('redis'); | ||
|
||
// create a new redis client and connect to our local redis instance | ||
var client = redis.createClient({ | ||
host: 'redis' | ||
}); | ||
|
||
// if an error occurs, print it to the console | ||
client.on('error', function (err) { | ||
console.log("Error " + err); | ||
}); | ||
|
||
client.flushdb( function (err, succeeded) { | ||
console.log(succeeded); // will be true if successfull | ||
}); | ||
|
||
function cacheFilter(key) { | ||
return function(key, req, res, next) { | ||
client.get(key, function(error, result) { | ||
if (result) { | ||
console.log('>> source - cache'); | ||
res.json(JSON.parse(result)); | ||
} else { | ||
next(); | ||
} | ||
}); | ||
}.bind(null, key); | ||
} | ||
|
||
function cache(key, value) { | ||
// Cache last 10 hours | ||
client.set(key, JSON.stringify(value), 'EX', 36000); | ||
} | ||
|
||
module.exports = { | ||
cacheFilter, cache | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters