【问题标题】:Execute code from setTimeOut after the response has been sent to the client in node js is a bad practice?在节点 js 中将响应发送到客户端后从 setTimeOut 执行代码是一种不好的做法?
【发布时间】:2021-04-20 17:58:15
【问题描述】:

我想在响应发送到客户端后调用 setTimeOut 3分钟后更改数据库中的值,有什么问题吗?

app.get("/route",(req,res,next) => {

// update value in db
// then send the value in the response
res.status(200).json({newValue : value}).end();

setTimeout(()=>{
// change the value in the db after 3 minutes
},180000)

}) 

【问题讨论】:

  • 我在这里为我的问题添加更多信息,我想要执行的任务是向 MongoDB 插入一些随机代码,用于 SMS 代码,但我想在 3 分钟后更改值,mongo中有什么功能可以做到这一点吗?或者我最好的解决方案是在节点服务器中执行此操作?如果我仍然像上面那样以原始方式执行此操作,如果我获得大量流量,是否会导致其他客户端调用服务器出现问题?

标签: node.js rest express http settimeout


【解决方案1】:

使用setTimeout 做一些工作没有问题,但这是一个幼稚的解决方案。如果服务器宕机,任务将丢失。所以更好的方法是使用像node-cron 这样的调度程序,它将在每分钟轮询数据库以查看是否有任何行符合条件。如果您将应用程序更改为这样的架构,那么您只需向表中添加一行,其到期时间为T+3 minutes,cron 作业将检查表中是否有任何未处理的条目并处理这些数据。

var cron = require('node-cron');

cron.schedule('* * * * *', () => {
  console.log('running a task every minute');
  /* Get entries from database table which has a timestamp < now and is unprocessed and act on those data */
 
 // do the processing

 // mark the row as processed
});

那么你的路线就是

app.get("/route",(req,res,next) => {

// update value in db
// then send the value in the response
res.status(200).json({newValue : value}).end();

// write a row to database table with expiry now() + 3 minutes

}) 

【讨论】:

  • 谢谢 我一定会看看这个模块! ,你知道它是否也适用于 MongoDB 吗?
  • 是的,它适用于 mongoDB,事实上,它是一种与数据库无关的方法。
  • 在mongodb中,可以通过设置TTL来自动过期文档。看到这个medium.com/@Baresse/…
  • 是的,我熟悉 TTL,我用它来清除会话,问题是我的 SMS 代码不是一个文档,它是另一个文档中的一个字段,我想我会尝试 node-cron 并且会见
猜你喜欢
  • 2011-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-19
  • 1970-01-01
  • 2018-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多