user19292442
user19292442

Reputation:

Data caching every 10 minutes (Redis/Node.js)

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

Answers (1)

Tharun Vemula
Tharun Vemula

Reputation: 95

To cache your data, you can do the following steps:

  1. Setup your Redis Instance
  2. Since you want to cache station_status query, consider station_id as the key
  3. Store the data in Redis station_id as the key and the corresponding data object as value, and set an expiration time of 10 minutes, (600s):
  4. You can do the above as follows, redisClient.setex(key, 600, JSON.stringify(fetchedData));
  5. In the above code, setex is used to set the value of the key with a timeout of 600 seconds (10 minutes). The fetchedData is converted to a JSON string using JSON.stringify before storing it in Redis
  6. Before making a query to your MySQL database, check if the data exists in the Redis cache. If it does, retrieve it; otherwise, fetch the data from the MySQL database and store the data in Redis as described in step 3.

Upvotes: 0

Related Questions