Node.js和CPU密集型请求 [英] Node.js and CPU intensive requests

查看:148
本文介绍了Node.js和CPU密集型请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始修改Node.js HTTP服务器,并且非常喜欢编写服务器端Javascript,但有些东西阻止我开始使用Node.js作为我的Web应用程序。

I've started tinkering with Node.js HTTP server and really like to write server side Javascript but something is keeping me from starting to use Node.js for my web application.

我理解整个异步I / O概念,但我有点担心程序代码非常占用CPU的边缘情况,例如图像处理或排序大数据集。

I understand the whole async I/O concept but I'm somewhat concerned about the edge cases where procedural code is very CPU intensive such as image manipulation or sorting large data sets.

据我所知,服务器对于简单的网页请求非常快,例如查看用户列表或查看博客帖子。但是,如果我想编写非常CPU密集型代码(例如在管理员后端)生成图形或调整数千个图像的大小,请求将非常慢(几秒钟)。由于此代码不是异步的,因此在几秒钟内发送到服务器的每个请求都将被阻止,直到我的慢请求完成为止。

As I understand it, the server will be very fast for simple web page requests such as viewing a listing of users or viewing a blog post. However, if I want to write very CPU intensive code (in the admin back end for example) that generates graphics or resizes thousands of images, the request will be very slow (a few seconds). Since this code is not async, every requests coming to the server during those few seconds will be blocked until my slow request is done.

一个建议是使用Web Workers进行CPU密集型任务。但是,我担心网络工作者会很难编写干净的代码,因为它的工作原理是包含一个单独的JS文件。如果CPU密集型代码位于对象的方法中该怎么办?为每个CPU密集型方法编写一个JS文件真是太糟糕了。

One suggestion was to use Web Workers for CPU intensive tasks. However, I'm afraid web workers will make it hard to write clean code since it works by including a separate JS file. What if the CPU intensive code is located in an object's method? It kind of sucks to write a JS file for every method that is CPU intensive.

另一个建议是生成一个子进程,但这会使代码更难维护。

Another suggestion was to spawn a child process, but that makes the code even less maintainable.

有任何建议可以克服这个(感知的)障碍吗?如何使用Node.js编写干净的面向对象代码,同时确保CPU重任务执行异步?

Any suggestions to overcome this (perceived) obstacle? How do you write clean object oriented code with Node.js while making sure CPU heavy tasks are executed async?

推荐答案

您需要的是任务队列!将长时间运行的任务移出Web服务器是一件好事。将每个任务保存在单独的js文件中可以促进模块化和代码重用。它迫使您考虑如何以一种方式构建程序,从而使程序更容易调试和维护。任务队列的另一个好处是工作人员可以用不同的语言编写。只需弹出一个任务,完成工作,然后写回来。

What you need is a task queue! Moving your long running tasks out of the web-server is a GOOD thing. Keeping each task in "separate" js file promotes modularity and code reuse. It forces you to think about how to structure your program in a way that will make it easier to debug and maintain in the long run. Another benefit of a task queue is the workers can be written in a different language. Just pop a task, do the work, and write the response back.

类似这样的事情 https://github.com/resque/resque

以下是来自github的文章,了解他们为什么建造它 http://github.com/blog/542-introducing-resque

Here is an article from github about why they built it http://github.com/blog/542-introducing-resque

这篇关于Node.js和CPU密集型请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆