Redis (Cache)
....
Nested Hash
At top level we still have keys but the value to that key is not simple string instead it's own nested object. In order to create nested hash we use hset('spanish', 'red', 'rojo')
where spanish
is the main key, red
is another key and rojo
is actual value.
To retrieve value we use similar syntax. hget('spanish', 'red', (err, val) => console.log(val))
const redisValue = {
spanish: {
red: 'rojo',
orange: 'naranja'
},
german: {
red: 'rot',
orange: 'orange',
blue: 'blau'
}
}
client.hset('spanish','red','rojo');
client.get('spanish','red',(err,val) => {})
Caching Key
We should always set key that are consistent but unique between query executions.
- Do we have a cached data in redis
- If yes request right away and return
- if no, query to database and update our cache store.
const cached = await client.get(req.user.id);
if(cached) {
return res.send(JSON.parse(cached));
}
const blogs = await Blog.find({_user: req.user.id })
res.send(blogs)
client.set(req.user.id, JSON.strigify(blogs))