More caching examples in node.js

By using expirations, we can set our server to hold on to one of our queries for a specified amount of time. This is useful if we know our data is changing, but we want to strike a balance between fresh queries to the database and caching.

So, using the code we used previously in our books route, lets add the following line after we set the value of the key:

redis.expire("books", 10);

Now, the first time we request this resource, we'll query the database and set the key in Redis, then set that key's value to expire in 10 seconds. The second time, within 10 seconds, we'll return the value stored in Redis for this key. The third time, after 10 seconds, we'll execute the same logic as the first request. See below for the results.

Great, so now we can set cache to expire after a certain amount of time. In a real world environment, you'll probably want to use data to determine what your expires should be.