登录
首页 >  文章 >  前端

Cron 作业中聚合的力量和成本效益

来源:dev.to

时间:2024-09-24 19:15:57 117浏览 收藏

大家好,我们又见面了啊~本文《Cron 作业中聚合的力量和成本效益》的内容中将会涉及到等等。如果你正在学习文章相关知识,欢迎关注我,以后会给大家带来更多文章相关文章,希望我们能一起进步!下面就开始本文的正式内容~

Cron 作业中聚合的力量和成本效益

在开发我的 saas 产品时,我发现,对于 10k 用户,您每天需要 10,001 次查询,并定期进行数据库查询来重置积分或免费提示。通过智能聚合,无论您有 10k 还是 100k 用户,您都只需要 2 次查询!

首先,让我给您一些 mongodb 生产数据库的成本审查(10k 和 1 年):

正常方式,每日查询:10,001
年度查询:10,001 x 365 = 3,650,365 次查询
年度费用:3,650,365 x 0.001 美元 = 3,650.37 美元

聚合方式,每日查询:2
年度查询:2 x 365 = 730 次查询
年度费用:730 x 0.001 美元 = 0.73 美元

节省:3,650.37 - 0.73 = 3,649.64 美元(近 40 万泰铢)

太棒了,现在看看传统的查询方法(为每个用户进行一个查询)

const resetlimitsforusers = async () => {
  const users = await user.find({ /* conditions to select users */ });

  for (const user of users) {
    if (user.plan.remaining_prompt_count < 3 || user.plan.remaining_page_count < 3) {
      user.plan.remaining_prompt_count = 3;
      user.plan.total_prompt_count = 3;
      // save updated plan
      await user.plan.save();
    }
  }
};

这里,如果您有 10,000 个用户,这会导致 10,001 个查询(每个用户 1 个,加上用于获取用户的初始查询) - 这是巨大的..

现在是英雄条目,[看起来有点困难,但它可以节省大量的钱]

const resetPlanCounts = () => {
  cron.schedule('* * * * *', async () => {
    try {
      const twoMinutesAgo = new Date(Date.now() - 2 * 60 * 1000); // 2 minutes ago

      const usersWithRegisteredPlan = await User.aggregate([
        {
          $match: {
            createdAt: { $lte: twoMinutesAgo },
            plan: { $exists: true }
          }
        },
        {
          $lookup: {
            from: 'plans',
            localField: 'plan',
            foreignField: '_id',
            as: 'planDetails'
          }
        },
        {
          $unwind: '$planDetails'
        },
        {
          $match: {
            'planDetails.name': 'Registered',
            $or: [
              { 'planDetails.remaining_prompt_count': { $lt: 3 } },
              { 'planDetails.remaining_page_count': { $lt: 3 } }
            ]
          }
        },
        {
          $project: {
            planId: '$planDetails._id'
          }
        }
      ]);

      const planIds = usersWithRegisteredPlan.map(user => user.planId);

      if (planIds.length > 0) {
        const { modifiedCount } = await Plan.updateMany(
          { _id: { $in: planIds } },
          { $set: { remaining_prompt_count: 3, total_prompt_count: 3, remaining_page_count: 3, total_page_count: 3 } }
        );

        console.log(`${modifiedCount} plans reset for "Registered" users.`);
      } else {
        console.log('No plans to reset for today.');
      }
    } catch (error) {
      console.error('Error resetting plan counts:', error);
    }
  });
};

这就是您如何运行 cron 作业 [它在特定时间自动运行] 来更新所有 10k 用户积分或限制,这可以在一年内节省超过 3600 美元。

作者,
姓名:mahinur ra​​hman
联系方式:dev.mahinur.rahman@gmail.com

到这里,我们也就讲完了《Cron 作业中聚合的力量和成本效益》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>