Reputation:
I want to store (cache) my data once fetched from my MYSQL db every 10 minutes (because my data is updated every 10 minutes from my python environment) in order to optimize my app (in speed), how can i do this with Redis (i'm a full beginner in fullstack dev) ?
Here is the index.js from my server dir :
const express = require('express');
const db = require('./config/db')
const cors = require('cors')
const redis = require('redis');
const client = redis.createClient();
const app = express();
const PORT = 8800;
app.use(cors());
app.use(express.json())
app.get("/", (req, res)=>{
res.send("MySQL Server is running")
})
app.get("/station_status", (req, res)=>{
db.query("SELECT station_id, available_docks, available_electronic_bikes,available_mechanical_bikes, available_bikes, status, MAX(last_update) as last_update,district_name FROM station_status GROUP BY station_id", (err, result)=>{
if(err){
console.log(err)
}else{
res.send(result)
}
})
})
app.get("/station_information", (req, res)=>{
db.query("SELECT station_id, name, lat, lon, capacity FROM station_information", (err, result)=>{
if(err){
console.log(err)
}else{
res.send(result)
}
})
})
app.listen(PORT, ()=>{
console.log('Connected to server')
console.log(`Server is running on ${PORT}`)
how can i implement Redis in order to cache the station_status query every 10 minutes so i can directly grab the data from the cache in order to execute the query every time i need it ?
Upvotes: 0
Views: 597
Reputation: 95
To cache your data, you can do the following steps:
station_status
query, consider station_id
as the keystation_id
as the key and the corresponding data object as value, and set an expiration time of 10 minutes, (600s):redisClient.setex(key, 600, JSON.stringify(fetchedData));
Upvotes: 0