如何制作分布式node.js应用程序? [英] How to make a distributed node.js application?

查看:114
本文介绍了如何制作分布式node.js应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建node.js应用程序非常简单。

Creating a node.js application is simple enough.

var app = require('express')();
app.get('/',function(req,res){
    res.send("Hello world!");
});

但是假设人们迷上了你的 Hello World!申请并耗尽你的资源。如何在实践中扩大这个例子?我不明白,因为是的,您可以在不同的计算机上打开几个node.js实例 - 但是当有人访问 http://your_site.com/ 它直接针对特定的机器,即特定的端口,即特定的节点进程。怎么样?

But suppose people became obsessed with your Hello World! application and exhausted your resources. How could this example be scaled up on practice? I don't understand it, because yes, you could open several node.js instance in different computers - but when someone access http://your_site.com/ it aims directly that specific machine, that specific port, that specific node process. So how?

推荐答案

有很多方法可以解决这个问题,但归结为两件事:

There are many many ways to deal with this, but it boils down to 2 things:


  1. 能够为每台服务器使用更多核心

  2. 能够扩展到超过一台服务器。



node-cluster



对于第一个选项,您可以使用 node-cluster 或与seconde选项相同的解决方案。 node-cluster http://nodejs.org /api/cluster.html )本质上是一种内置的方法,可以将节点进程分成一个主服务器和多个工作服务器。通常,您需要1个主人和n-1到n个工人(n是您可用核心的数量)。

node-cluster

For the first option, you can user node-cluster or the same solution as for the seconde option. node-cluster (http://nodejs.org/api/cluster.html) essentially is a built in way to fork the node process into one master and multiple workers. Typically, you'd want 1 master and n-1 to n workers (n being your number of available cores).

第二个选项是使用负载均衡器,在多个工作人员之间(在同一台服务器上或服务器之间)分配请求。

The second option is to use a load balancer that distributes the requests amongst multiple workers (on the same server, or across servers).

这里你有多个选择。以下是一些:

Here you have multiple options as well. Here are a few:

  • a node based option: Load balancing with node.js using http-proxy
  • nginx: Node.js + Nginx - What now? (using more than one upstream server)
  • apache: (no clearly helpful link I could use, but a valid option)

还有一件事,一旦你开始有多个进程为请求提供服务,就不能再使用内存来存储状态,你需要一个额外的服务来存储共享状态,Redis( http://redis.io )是一个受欢迎的选择,但绝不是唯一的选择。

One more thing, once you start having multiple processes serving requests, you can no longer use memory to store state, you need an additional service to store shared states, Redis (http://redis.io) is a popular choice, but by no means the only one.

如果您使用cloudfoundry,heroku等服务,他们会为您设置它,因此您只需要担心应用程序的逻辑(并使用服务来处理s hared state)

If you use services such as cloudfoundry, heroku, and others, they set it up for you so you only have to worry about your app's logic (and using a service to deal with shared state)

这篇关于如何制作分布式node.js应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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