如何使用redis在缓存中存储数据?

编程入门 行业动态 更新时间:2024-10-05 19:17:18

如何使用redis在<a href=https://www.elefans.com/category/jswz/34/1771061.html style=缓存中存储数据?"/>

如何使用redis在缓存中存储数据?

我是后端开发和学习 nodejs 和 Mongodb 的新手 我正在为一家公司开发一个 api 作为实习项目,但我陷入了我的问题 将近 2 天,谁能帮我解决这个问题?

我想做的是当我用户从客户端点击 API 时,API 从正文中获取用户电子邮件并通过其电子邮件找到该用户 并找到它的宠物名字,如狗,猫等宠物是一个字符串,如果它找到一个具有相似宠物名称的用户并且如果一个用户找到具有相同宠物名称那么 它会给那个相似的用户回应,直到一切都很好

但是每个用户每天只能得到一个具有相同宠物名称的相似用户,所以我如何才能创建第二天的过期时间以及那一天之间的过期时间 如果用户再次尝试访问 API,它会给出相同的旧用户作为响应,但要执行所有这些操作,我需要跟踪用户 所以我使用 Nodecache 来存储用户电子邮件,但是问题来了,当我重新启动服务器时,缓存消失了如何解决这个问题?和存储 在 Redis 中缓存数据?

还有其他方法可以做我想做的事吗?

普通API:

router.post("/getuserwithpet", async (req, res) => {
    try {
        const { email } = req.body;

        const user = await User.findOne({ email: email });
        let pet = user.pet

        const count = await User.countDocuments({ pet: pet });
        if (count === 0) {
            return res.status(404).json({ error: "No users found with that pet" });
        }
        const randomUser = await User.aggregate([
            { $match: { pet: pet, email: { $ne: email } }, },
            { $sample: { size: 1, }, },
            { $project: { name: 1, username: 1, profileImg: 1 } },
        ]);
        res.json(randomUser);
    } catch (err) {
        console.log(err);
        res.status(500).json({ error: err });
    }
});

节点缓存接口:

import NodeCache from 'node-cache';
const cache = new NodeCache();

router.post("/getuserwithpet", async (req, res) => {
    try {
        const { email } = req.body;

        // Try to retrieve data from cache
        const cachedData = cache.get(email);

        if (cachedData) {
            // If cached data is still valid, return it
            const now = new Date();
            if (cachedData.expiration > now) {
                return res.json(cachedData.data);
            }
        }

        // Retrieve user from database
        const user = await User.findOne({ email: email });
        let pet = user.pet;

        const count = await User.countDocuments({ pet: pet });
        if (count === 0) {
            return res.status(404).json({ error: "No users found with that pet" });
        }

        let dataToCache;

        if (cachedData && cachedData.data) {
            dataToCache = cachedData.data;
        } else {
            dataToCache = await User.aggregate([
                { $match: { pet: pet, email: { $ne: email } }, },
                { $sample: { size: 1, }, },
                { $project: { name: 1, username: 1, profileImg: 1 } },
            ]);
        }

        const now = new Date();
        const expiration = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, Math.floor(Math.random() * 6) + 5, 0, 0, 0);
        const dataToCacheWithExpiration = { data: dataToCache, expiration: expiration };
        cache.set(email, dataToCacheWithExpiration);
        res.json(dataToCache);
    } catch (err) {
        console.log(err);
        res.status(500).json({ error: err });
    }
});
回答如下:

更多推荐

如何使用redis在缓存中存储数据?

本文发布于:2024-05-30 12:00:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770474.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缓存   如何使用   数据   redis

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!