最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

网站源码admin38浏览0评论

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

如何使用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 });
    }
});
回答如下:
发布评论

评论列表(0)

  1. 暂无评论