Contents
- Introduction to Redis
- What is Redis?
- Installation
- Basic Redis Commands
- Lists
- Sets
- Hashes
- Sample Redis application
Introduction to Redis
What is Redis?
Redis is an in-memory database with sub millisecond latency. Redis stands for Remote Dictionary Service. What makes redis so powerful is that, it stores the data in the memory and not in the slower disks. Every data point in the database is a key-value pair.
Redis is so popular because of it's speed. Unlike a relational database where the data is stored in slower hard disks, redis stores the data in RAM.
Due to the usage of RAM, Redis is volatile, meaning that when the system shuts down, your data is also lost. Hence, Redis is usually not used as a persistent database like MongoDb or PostgresSql and is instead used for caching.
Redis is not a replacement for your database, Instead it is build on top of your traditional database. Any data that needed to be accessed frequently can be stored in Redis.
When you need to access some data frequently
When the data base query is long and takes a lot of time to execute
Installation
brew install redis
Basic Redis Commands
Startup Commands
redis-server - To start Redis server use the command
To use the Redis CLI open a new terminal and enter redis-cli and to close it use quit command
Basic commands
SET name your-name - Setting a value
GET name - Get the above value
DEL name - Delete a key-value by
EXISTS name - To check if a key exist
KEYS * - Get all keys
flushall - Clear all the data
Expiration
ttl key-name - Check how long a key has before being deleted automatically. if the result is -1 it means ttl(Time To Live) is not set and it wont expire.
expire key-name 10 - Set a ttl of 10 seconds.
setex name 10 your-name - To set a ttl while setting a key value pair.
Lists
Lists are useful when we want to implement a queue or stack. Like in case of a messenger app, where we cache some of the recent messages.
lpush fruits apple - Push an item into the left of a list.
rpush fruits mango - Push an item into the right of a list.
lrange fruits 0 -1 - Get all the items from the list. The -1 stands for the index at the end of the list.
LPOP fruits - Removes the leftmost item in the list.
RPOP fruits - Removes the rightmost item in the list.
Sets
Sets are similar to lists. What makes a Set different is that it will only store unique values.
SADD todo "read book" - To add item into a set. (note: if we try to add "read book" again it won't be added as it is a duplicate)
SMEMBERS todo - Show all the items in the todo set.
SREM todo "read book" - To remove item from set.
Hashes
Whereas LISTs and SETs in Redis hold sequences of items, Redis HASHes store a mapping of keys to values.
HSET person name John - Here name is the key and John is the value.
HGET person name - This returns the value associated with the key name and in this case it returns John.
HGETALL person - Get all the info about person.
HDEL person name - Remove the name property.
HEXISTS person name - To check if the property exists.
Sample Redis Application
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const redis = require('redis');
// Default Expiration time for redis cache
const EXPIRATION_TIME = 3600;
// create redis client
const redisClient = redis.createClient();
const app = express();
app.use(cors());
// photos endpoint
// GET request from: https://jsonplaceholder.typicode.com/photos
app.get('/photos', async (req, res) => {
// set albumId
const albumId = req.query.albumId;
// make the request
const { data } = await axios.get(
'https://jsonplaceholder.typicode.com/photos',
{ params: { albumId } }
);
// Set data to Redis
redisClient.SETEX('photos', EXPIRATION_TIME, JSON.stringify(data));
// send the response
res.json(data);
// Check if photos is in redis cache
redisClient.GET('photos', async (err, photos) => {
if (err) console.log(err);
if (photos !== null) {
console.log('photos is in redis cache');
// if photos is in cache, return photos from cache
res.json(JSON.parse(photos));
}
else {
console.log('photos is not in redis cache');
// make the request
const { data } = await axios.get(
'https://jsonplaceholder.typicode.com/photos',
{ params: { albumId } }
);
// Set data to Redis
redisClient.SETEX('photos', EXPIRATION_TIME, JSON.stringify(data));
// send the response
res.json(data);
}
})
});
// GET request from: https://jsonplaceholder.typicode.com/:id
app.get('/photos/:id', async (req, res) => {
const { data } = await axios.get(
`https://jsonplaceholder.typicode.com/photos/${req.params.id}`
)
res.json(data);
});
app.listen(3000, () => {
console.log('Listening on localhost:3000');
})
Comments