我什么时候需要在 Heroku 中使用工作进程

When do I need to use worker processes in Heroku

我有一个 Node.js 应用程序,该应用程序有一小部分用户,目前使用单个 Web 进程构建。我正在考虑添加一个保存后触发器,当一条记录添加到我的 table 之一时,该触发器将被调用。当执行保存触发器后,我想对外部 API 执行大量 IO 操作。 IO 操作的数量取决于记录上数组列中元素的数量。因此,在这个特定的 table.

中保存每条记录后,我可能会执行大量异步操作

我考虑过按照 Worker Dynos, Background Jobs and Queueing. The article gives as a rule of thumb that tasks that take longer than 500 ms be moved to background job. However, after working through the example using RabbitMQ (Asynchronous Web-Worker Model Using RabbitMQ in Node) 中的建议将这项工作移至后台作业,但我不认为值得花时间来设置所有内容。

那么,我的问题是:

For an app with a limited amount of concurrent users, is it ok to leave a long-running function in a web process?

这更像是一个偏好问题,而不是任何问题。

总的来说,我说不——这不好……但这是基于在 heroku worker 中构建 rabbitmq 服务的经验 运行,并不认为这是一件困难的事情。

稍加练习,您可能会发现这是更简单的解决方案,就像我所做的那样(它允许更简单的代码和更健壮的代码,因为它将网络与后台处理器分开 - 允许每个 运行 不直接了解对方)

If I eventually decide to send this work to a background job it doesn't seem like it would be that hard to change my after save trigger. Am I missing something?

你是不是漏了什么?不是真的

只要您以结构良好和模块化的方式编写当前的网络进程代码,将其移至后台进程通常不是什么大问题

人们不得不将代码移到后台而引起的大部分恐慌来自于将他们的代码与 HTTP 请求/响应过程紧密耦合(我从个人经验中知道这会有多痛苦)

Is there a way to do this that is easier than implementing a message queue?

分布式计算和后台处理有很多选择。我个人喜欢 RabbitMQ 和它使用的消息传递模式。

我建议您尝试一下,看看它是否适合您。

其他选项包括带有 pub/sub 库的 Redis,使用直接 HTTP API 调用另一个网络服务器,或者只是在后台进程中使用计时器来检查数据库表给定频率并根据它找到的数据获得代码 运行。

p.s。如果您想深入了解带节点的 RMQ,您可能会发现我对 RabbitMQ For Developers 课程感兴趣:http://rabbitmq4devs.com