Node.js工作者/后台进程 [英] Node.js workers/background processes
问题描述
如何在node.js中创建和使用后台作业?
How can I create and use background jobs in node.js?
我遇到了两个库(node-resque和node-worker),但是想知道是否还有更多使用的库.
I've come across two libs (node-resque and node-worker) but would like to know if there's something more used.
推荐答案
我对此做了一些研究,我会这样做.
I did some research on this and I would do it like this.
-
安装 beanstalkd .另一个消息队列,但,该消息队列支持 DELAYED PUTS .如果您从源代码进行编译,它将变得更加困难,因为它取决于 libevent (例如memcached ).但是话又说回来,我认为您不必从源代码进行编译,因为有很多二进制包可用.例如,在Ubuntu上,您可以通过发出以下命令来安装beanstalkd:
Install beanstalkd. Another message queue, BUT this one supports DELAYED PUTS. If you compile from source it is going to be a little harder because it depends on libevent(like memcached). But then again, I don't think you have to compile it from source, because there are a lot of binary packages available. For example on Ubuntu you can install beanstalkd by issuing the command:
sudo apt-get install beanstalkd
node-beanstalk-client
-
安装beantalkd客户端库.我发现的最好的是 node-beanstalk-client .因为在beantalkd客户端库列表中没有/没有提到该库(然后再次将条目添加到列表中,所以我将添加该条目).与其他库相比,我更喜欢此库的原因是:
Install a beanstalkd client library. The best one I found was node-beanstalk-client. Because on the beanstalkd client library list this library isn't/wasn't mentioned(Then again I can add entries to the list, so I will add this one). The reasons I prefer this library over the others are:
- Npm软件包:我喜欢使用npm软件包来安装客户端库.其他都没有.
- 主动开发:我更喜欢具有更高/更高提交次数的库.
- Npm package: I liked to use a npm package to install client library. The others did not have any.
- Active development: I prefer libraries which have later/more commits.
因此,在安装 npm (
So to install it, after you have installed npm(the write way) you would just issue the following command:
npm install beanstalk_client
代码
consumer.js
var client = require('beanstalk_client').Client;
client.connect('127.0.0.1:11300', function(err, conn) {
var reserve = function() {
conn.reserve(function(err, job_id, job_json) {
console.log('got job: ' + job_id);
console.log('got job data: ' + job_json);
console.log('module name is ' + JSON.parse(job_json).data.name);
conn.destroy(job_id, function(err) {
console.log('destroyed job');
reserve();
});
});
}
reserve();
});
首先启动使用者:
node consumer.js
下一次启动producer.js
.执行producer.js
后五秒钟(我指定的延迟),consumer.js
将处理该消息.
Next start producer.js
. Five seconds(delay I specified) after you execute producer.js
, consumer.js
will process the message.
var client = require('beanstalk_client').Client;
client.connect('127.0.0.1:11300', function(err, conn) {
var job_data = {"data": {"name": "node-beanstalk-client"}};
var priority = 0;
var delay = 5;
var timeToRun = 1;
conn.put(priority, delay, timeToRun, JSON.stringify(job_data), function(err, job_id) {
console.log('put job: ' + job_id);
process.exit();
});
});
开始发布:
node producer.js
这篇关于Node.js工作者/后台进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!