如何使用redis来改善我的nodejs API的响应时间?

thtygnil  于 2023-04-19  发布在  Redis
关注(0)|答案(1)|浏览(121)

如何使用Redis来改善我的nodejs API的响应时间?我试图使用Redis来改善我的响应时间,但当我使用它时,它比我的正常api花费更长的时间,当我不使用Redis时,它在52- 58 ms内获取数据,但当我使用Redis时,它花费更长的时间,它在响应时间内花费60- 66 ms如何解决这个问题,我检查了我的位置,它都是正确的
如何提高响应时间?

const Redis = require('ioredis');
const redisClient = new Redis({
    port: 16545,
    host: 'redis-16545.c305.ap-south-1-1.ec2.cloud.redislabs.com',
    password: 'mypass',
});

router.get('/posts', async (req, res) => {
    try {
        const cacheKey = `posts:${req.query.page || 1}`;
        const cacheTTL = 60;
        const cachedData = await redisClient.get(cacheKey);
        if (cachedData) {
            console.log('Data fetched from Redis cache');
            return res.json(JSON.parse(cachedData));
        }
        const page = Number(req.query.page) || 1;
        const limit = Number(req.query.limit) || 50;
        const skip = (page - 1) * limit;
        const result = await User.aggregate([
            { $project: { posts: 1 } },
            { $unwind: '$posts' },
            { $project: { postImage: '$posts.post', date: '$posts.date' } },
            { $sort: { date: -1 } },
            { $skip: skip },
            { $limit: limit },
        ]);
        await redisClient.set(cacheKey, JSON.stringify(result), 'EX', cacheTTL);
        console.log('Data fetched from MongoDB and cached in Redis');
        res.json(result);
    } catch (err) {
        console.error(err);
        res.status(500).json({ message: 'Internal server error' });
    }
});
z5btuh9x

z5btuh9x1#

可能是操作JSON.parse占用了更多的运行时间?..🤔
是否尝试使用redisnpm包,最新版本为4.6.5

你可以直接将value对象保存在redis中,而不需要在set上进行字符串化,在get上进行解析

例如:

import { createClient } from 'redis';
...
// for set:
await client.json.set(cacheKey, '$', cachedData);
...
// for get:
const cachedData = await client.json.get(cacheKey);
if (cachedData) {
    console.log('Data fetched from Redis cache');
    return res.json(cachedData);
}
...

https://www.npmjs.com/package/redis
https://github.com/redis/node-redis/tree/d65a641b2db96c6d63a2a51c43e823aba8256e28/packages/json

相关问题