you can run docker compose up -d to create the docker image/container of the redis server
version: "3.8"
services:
cache:
image: redis:6.2-alpine
restart: always
ports:
- "6379:6379"
command: redis-server --save 20 1 --loglevel warning --requirepass eYVX7EwVmmxKPCDmwMtyKVge8oLd2t81
volumes:
- cache:/data
volumes:
cache:
driver: localPrerequisites
npm install express redis dotenv uuidREDIS_HOST='YOUR_REDIS_HOST'
REDIS_PORT='YOUR_REDIS_PORT'
REDIS_PASSWORD='YOUR_REDIS_PASSWORD'you can ignore the REDIS_PASSWORD if you don't have one
Create a src/config folder
const redis = require("redis");
require("dotenv").config({ path: ".env.local" });
class Redis {
async connect() {
return await redis
.createClient({
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
password: process.env.REDIS_PASSWORD,
})
.on("error", (err) => console.log("Redis Client Error", err))
.connect();
}
}
module.exports = new Redis();If you only want to connect to your local redis server you can just use redis.createClient()
In my case I connect to my redis with host,port and password properties within the createClient()
add setValue() into the Redis class
async valueSet(key, value) {
const client = await this.connect();
client.set(key, value);
}add get() into the Redis class
async get(key) {
const client = await this.connect();
return await client.get(key);
}With all of the above stuffs we are done configuring Redis methods and ready to test
before implementing the index.js file we need a UUID generator method to make our redis key unique
Create utils folder and a UUIDGenerator.js file
const { v4: uuidv4 } = require("uuid");
const generateUUID = () => {
return uuidv4();
};
module.exports = generateUUID;Create index.js file
const express = require("express");
const app = express();
const Redis = require("./src/config/redis");
const generateUUID = require("./src/utils/UUIDGenerator");
// connect to redis server
Redis.connect();
app.use(express.json());
// a POST request to set value to Redis Database
app.post("/setkey", (req, res) => {
try {
const value = req.body.value;
const uuid = generateUUID();
const key = req.body.key + ":" + uuid;
Redis.valueSet(key, value);
res.status(201).json({
status: "success",
message: "successfully added",
info: `${key} : ${value}`,
});
} catch (error) {
console.log(error);
res.status(500).json({
status: "fail",
message: error,
});
}
});
// a GET request to get value from Redis Database by Key
app.get("/getkey", async (req, res) => {
try {
const key = req.body.key;
const value = await Redis.get(key);
res.status(200).json({
status: "success",
message: "retreived successfully",
info: value,
});
} catch (error) {
res.status(500).json({
status: "fail",
message: error.message(),
});
}
});
app.listen(8090, () => {
console.log("server is running on port: 8090....");
});Project Repository: https://github.com/metaphorlism/node-redis