好吧,我(天真地)尝试让公牛在sails应用程序中工作:最终,我希望有一个队列,我可以根据传入的路由向其中添加/删除/检查任务。
现在,根据我对sails的理解,要创建一个全局工作的排队系统,我必须在bootstrap.js中添加此设置。
/**
* Bootstrap
* (sails.config.bootstrap)
*
* An asynchronous bootstrap function that runs before your Sails app gets lifted.
* This gives you an opportunity to set up your data model, run jobs, or perform some special logic.
*
* For more information on bootstrapping your app, check out:
* https://sailsjs.com/config/bootstrap
*/
module.exports.bootstrap = function(done) {
// It's very important to trigger this callback method when you are finished
// with the bootstrap! (otherwise your server will never lift, since it's waiting on the bootstrap)
let Queue = require('bull');
let q = new Queue('test queue');
q.process(function(job, done){
console.log("starting job");
for(let i = 0; i<job.value; i+=1) {
console.log(i);
}
done();
});
q.add({'value':10});
global.DirectUpdateQueue = q;
return done();
};根据上面的代码,sails可以很好地启动,并且在路由中我可以看到global.DirectUpdateQueue存在。
然而,不起作用的是队列中的任务被执行。-我在控制台看不到任何日志(至少应该是“starting job”)。当nI在处理函数中放置断点时,代码也不会中断。
那么这是怎么回事呢?
编辑:这可能是因为我没有设置(本地) redis服务器吗?-我没有找到关于这个主题的任何信息,但我期望/希望bull.js在内部实际处理这个服务器,(更重要的是)不限于特定的(OS)环境。
发布于 2019-02-24 12:31:01
因此,首先,您必须确保您的服务器上安装了Redis。当创建一个队列时,你可以在下面的例子中传递Redis config,它是默认的。
然后在bootsrap.js中:
var Queue = require('bull');
var testQueue = new Queue('Website Queue', 'redis://127.0.0.1:6379');
testQueue.process(function(job, done){
console.log('job started');
setTimeout(function () {
console.log('10 seconds later');
console.log(job.data);
}, 10000)
done();
});
global.testQueue = testQueue; 然后,您可以从操作/控制器中执行以下操作:
testQueue.add({'value':10}); 发布于 2018-01-16 23:16:43
首先,您必须连接到Redis服务器
var testQueue = new Queue('test', {
redis: {
port: 6379,
host: '127.0.0.1',
password: 'secret'
}
});根据the doc的说法:
如果队列为空,则作业将被直接执行,否则将被放入队列中并尽快执行。
要访问作业中的数据,请使用job.data对象:
testQueue.process((job) => {
console.log("job with data 'foo' :", job.data.foo);
// example with Promise
return asynchTreatment()
.then(() => { console.log('treatment ok'); })
.catch((err) => { console.log('treatment ko :', err); }
}).on('completed', (job, result) => {
// Job completed with output result!
console.log('result :', result);
});
testQueue.add({ foo : 'bar' });EDIT 1 :
医生说:
它创建了一个新的队列,该队列持久保存在Redis中。每次实例化同一个队列时,它都会尝试处理前一个未完成会话中可能存在的所有旧作业。
因此,如果服务器重新启动,您不会丢失您的作业。
发布于 2018-03-05 15:17:12
只需在for循环中使用job.data.value
for(let i = 0; i<job.data.value; i+=1) {
console.log(i);
}
https://stackoverflow.com/questions/48266274
复制相似问题