3. Caching If you use some infrequently changing data, you should cache them and improve performance. For example, the following code is an example of getting the latest post and showing it: ?
1234567891011 |
var
router = express.Router();
router.route(
‘/latestPosts‘
).get(
function
(req, res) {
Post.getLatest(
function
(err, posts) {
if
(err) {
throw
err;
}
res.render(
‘posts‘
, { posts: posts });
});
});
|
If you don't post more often, you can cache the list of posts and then clean them up after a while. For example, we can use the Redis module to achieve this goal. Of course, you must have Redis on your server. You can then use a client called Node_redis to save the key/value pair. The following example shows how we can cache posts: ?
1234567891011121314151617181920 |
var
redis = require(
‘redis‘
),
client = redis.createClient(
null
,
null
, { detect_buffers:
true
}),
router = express.Router();
router.route(
‘/latestPosts‘
).get(
function
(req,res){
client.get(
‘posts‘
,
function
(err, posts) {
if
(posts) {
return
res.render(
‘posts‘
, { posts: JSON.parse(posts) });
}
Post.getLatest(
function
(err, posts) {
if
(err) {
throw
err;
}
client.set(
‘posts‘
, JSON.stringify(posts));
res.render(
‘posts‘
, { posts: posts });
});
});
});
|
See, let's check the Redis cache first to see if there are any posts. If so, let's take a list of these posts from the cache. Otherwise we will retrieve the database contents and then cache the results. Also, after a certain amount of time, we can clean up the Redis cache so that we can update the content. |