当涉及到如何在NodeJS ( Heroku )应用程序上实现不同的工作人员时,希望了解如何构造我的应用程序。
我的路由器打开了两个终点。一个接收GET请求,另一个接收具有某些主体内容的POST请求。
const Queue = require("bull");
// Create / Connect to a naned worked queue
let workQueue = new Queue("work", client);
router.post("/job/get-data/:id", ensureAuth, async (req, res) => {
let job = await workQueue.add({
filename: req.params.id,
arguments: req.body.data,
});
// Does not redirect if the POST request is made using Javascript
res.json({ id: job.id });
});
router.post("/job/perform-action/:id", ensureAuth, async (req, res) => {
let job = await workQueue.add({ id: req.params.id, type: req.body.type });
res.json({ id: job.id });
});现在,我对两个请求使用相同的队列。这是我的worker.js
const client = require("../config/redis");
let throng = require("throng");
let Queue = require("bull");
let workers = process.env.WEB_CONCURRENCY || 1;
let maxJobsPerWorker = 50;
let workQueue = new Queue("work", client);
function start() {
workQueue.process(maxJobsPerWorker, __dirname + "/processor.js");
}
throng({ workers, start })最后,这是processor.js文件:
const db = require("../config/db");
const scrapperController = require("../controller/scrapperController");
const awsController = require("../controller/awsController");
module.exports = async function (job) {
// We need to restart the Mongoose process here so it knows what database to search
db();
try {
let scrappedData = null;
if (job.data.arguments) {
// With argument, wants to get data
scrappedData = await scrapperController.getData(
job.data.filename,
job.data.arguments
);
await awsController.uploadFile(job.data.filename, scrappedData);
return { value: "Success" };
} else {
// With no arguments, whats to perform action
scrappedData = await scrapperController.performAction(job.data.id);
return { value: csvFileName };
}
} catch (error) {
return Promise.reject("Unable to scrape data", error);
}
};有谁知道如何把这两个终点分给不同的工人吗?也许一位员工会被称为“获取信息”,而另一位则会被称为“行动”。
我的想法是创建不同的文件来引用不同的工作人员,并链接到不同的处理器文件。
我的另一个想法是完全丢失processor.js文件,并创建执行不同操作的精程序工作文件。
我对工人和他们的“工作方式”都很陌生,所以我很难把我的注意力集中在他们身上。
对上述代码的任何其他改进将是非常欢迎的。
谢谢!
发布于 2022-09-06 21:29:29
我会创建不同的工作队列,所以
let workQueue = new Queue("work", client);在app.js中你会有
let getInfoQueue = new Queue("getInfo", client);
let doActionQueue = new Queue("doAction", client);然后您将调用每个队列的名称。
let getInfoQueue = new Queue("getInfo", client);
let doActionQueue = new Queue("doAction", client);
function start() {
getInfoQueue.process(maxJobsPerWorker, __dirname + "/getInfo.js");
doActionQueue.process(maxJobsPerWorker, __dirname + "/doAction.js");
}或者您可以直接在.process()方法中运行代码
https://stackoverflow.com/questions/64195314
复制相似问题