简体   繁体   English

是否可以在 NodeJS 中使用带有工作线程的服务?

[英]Is it possible to consume a service with worker threads in NodeJS?

I'm coding in NodeJS, I'm trying to make an API service which use multithreading internally, I've read many worker-threads tutorials, but I haven't found a solution.我正在使用 NodeJS 进行编码,我正在尝试制作一个在内部使用多线程的 API 服务,我已经阅读了许多工作线程教程,但我还没有找到解决方案。

In classes/controller.js:在类/controller.js 中:

const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
const os = require('os');
...
var threadN = function()
{
    if (isMainThread)
    {
        module.exports = function parseJSAsync(script)
        {
            return new Promise
            (
                (resolve, reject) =>
                {
                    const worker = new Worker(filename, {workerData: script});
                    worker.on('message', resolve);
                    worker.on('error', reject);
                    worker.on
                    (
                        'exit',
                        (code) =>
                        {
                            if (code !== 0)
                            {
                                reject(new Error(`Worker stopped with exit code ${code}`));
                            }
                        }
                    );
                }
            );
        };
        console.log('Thread ID:       ', Worker.threadId, "\nNumber of CPU's:", os.cpus().length);
    }
    else
    {
        console.log('Thread ID:       ', Worker.threadId, "\nNumber of CPU's:", os.cpus().length);
        const { parse } = require('some-js-parsing-library');
        const script = workerData;
        parentPort.postMessage(parse(script));
    }
};
...
exports.threadTest = function (req, res)
{
    threadN();
    res.json
    ({
        status: true,
        message: 'Hello World!'
    });
};

In routes/routes.js在路线/路线.js

var app = express();
...
app.get("/api_1.0/threadtest", model.threadTest);
...

When I consume it in Postman and see console changes I must get four messages (my CPU has four cores) with four thread ids, otherwise I got this:当我在 Postman 中使用它并看到控制台更改时,我必须收到四个带有四个线程 ID 的消息(我的 CPU 有四个内核),否则我得到了这个:

控制台响应

How can I consume an API service with worker_thread correctly?如何正确使用带有 worker_thread 的 API 服务?

Is it possible to consume a service with worker threads in NodeJS?是否可以在 NodeJS 中使用带有工作线程的服务?

Yes, if the worker thread and route for calling it is written properly.是的,如果调用它的工作线程和路由写得正确。

There are a number of things wrong here:这里有很多问题:

  1. You call threadN() in your route, but all that does in the main thread is assign parseJSAsync to module.exports .您在路由中调用threadN() ,但在主线程中所做的只是将parseJSAsync分配给module.exports It doesn't actually call anything in another thread or even create another thread.它实际上并没有在另一个线程中调用任何东西,甚至没有创建另一个线程。 It doesn't call parseJSAsync() .它不调用parseJSAsync()
  2. Assigning something to module.exports long after the module has been initialized is an anti-pattern that probably doesn't do anything useful.在模块初始化很久之后为module.exports分配一些东西是一种反模式,可能不会做任何有用的事情。 Any importing module already looked for what it might find in the exports, long before you assigned parseJSAsync to it.在您将parseJSAsync分配给它之前很久,任何导入模块都已经在导出中寻找它可能找到的内容。
  3. In threadTest() , you call threadN() , but that doesn't do anything useful for processing the request.threadTest()中,您调用threadN() ,但这对处理请求没有任何用处。 It seems more like you need to be calling parseJSAsync() and then using the promise that it returns.似乎您需要调用parseJSAsync()然后使用它返回的 promise 。

On a personal style note, I find workerThread code a ton easier to understand and work on if I put the mainThread code and workerThread code in separate files.就个人风格而言,如果我将 mainThread 代码和 workerThread 代码放在单独的文件中,我发现 workerThread 代码更容易理解和工作。 Then there's no context needed within the file in order to know which code is which.然后文件中不需要上下文来知道哪个代码是哪个。 IMO, it is a ton easier to understand and follow. IMO,它更容易理解和遵循。 I know that node.js documentation examples tend to use the single file approach, but after trying it, I moved to separate files as it was so much easier to work on, debug and understand.我知道 node.js 文档示例倾向于使用单文件方法,但在尝试之后,我转向单独的文件,因为它更容易处理、调试和理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM