NodeJS 初体验

[b]NodeJS对什么有好处?[/b]
Node 非常适合以下情况:在响应客户端之前,您预计可能有很高的流量,但所需的服务器端逻辑和处理不一定很多。Node 表现出众的典型示例包括:
[b]RESTful API[/b]
提供 RESTful API 的 Web 服务接收几个参数,解析它们,组合一个响应,并返回一个响应(通常是较少的文本)给用户。这是适合 Node 的理想情况,因为您可以构建它来处理数万条连接。它仍然不需要大量逻辑;它本质上只是从某个数据库中查找一些值并将它们组成一个响应。由于响应是少量文本,入站请求也是少量的文本,因此流量不高,一台机器甚至也可以处理最繁忙的公司的 API 需求。
[b]Twitter 队列[/b]
想像一下像 Twitter 这样的公司,它必须接收 tweets 并将其写入数据库。实际上,每秒几乎有数千条 tweet 达到,数据库不可能及时处理高峰时段所需的写入数量。Node 成为这个问题的解决方案的重要一环。如您所见,Node 能处理数万条入站 tweet。它能快速而又轻松地将它们写入一个内存排队机制(例如 memcached),另一个单独进程可以从那里将它们写入数据库。Node 在这里的角色是迅速收集 tweet,并将这个信息传递给另一个负责写入的进程。想象一下另一种设计(常规 PHP 服务器会自己尝试处理对数据库本身的写入):每个 tweet 都会在写入数据库时导致一个短暂的延迟,因为数据库调用正在阻塞通道。由于数据库延迟,一台这样设计的机器每秒可能只能处理 2000 条入站 tweet。每秒处理 100 万条 tweet 则需要 500 个服务器。相反,Node 能处理每个连接而不会阻塞通道,从而能够捕获尽可能多的 tweets。一个能处理 50,000 条 tweet 的 Node 机器仅需 20 台服务器即可。
[b]电子游戏统计数据[/b]
如果您在线玩过《使命召唤》这款游戏,当您查看游戏统计数据时,就会立即意识到一个问题:要生成那种级别的统计数据,必须跟踪海量信息。这样,如果有数百万玩家同时在线玩游戏,而且他们处于游戏中的不同位置,那么很快就会生成海量信息。Node 是这种场景的一种很好的解决方案,因为它能采集游戏生成的数据,对数据进行最少的合并,然后对数据进行排队,以便将它们写入数据库。使用整个服务器来跟踪玩家在游戏中发射了多少子弹看起来很愚蠢,如果您使用 Apache 这样的服务器,可能会 有一些有用的限制;但相反,如果您专门使用一个服务器来跟踪一个游戏的所有统计数据,就像使用运行 Node 的服务器所做的那样,那看起来似乎是一种明智之举。


安装完NodeJS后开发部署一个简单的web应用非常迅速。下面我们创建一个随机数字生成器 RESTful API。这个应用程序应该接受一个输入:一个名为 “number” 的参数。然后,应用程序返回一个介于 0 和该参数之间的随机数字,并将生成的数字返回给调用者。由于 “老板” 希望该应用程序成为一个广泛流行的应用程序,因此它应该能处理 50,000 个并发用户。
1. 创建文件random.js并输入以下代码

// these modules need to be imported in order to use them.
// Node has several modules. They are like any #include
// or import statement in other languages
var http = require("http");
var url = require("url");

// The most important line in any Node file. This function
// does the actual process of creating the server. Technically,
// Node tells the underlying operating system that whenever a
// connection is made, this particular callback function should be
// executed. Since we're creating a web service with REST API,
// we want an HTTP server, which requires the http variable
// we created in the lines above.
// Finally, you can see that the callback method receives a 'request'
// and 'response' object automatically. This should be familiar
// to any PHP or Java programmer.
http.createServer(function(request, response) {

// The response needs to handle all the headers, and the return codes
// These types of things are handled automatically in server programs
// like Apache and Tomcat, but Node requires everything to be done yourself
response.writeHead(200, {"Content-Type": "text/plain"});

// Here is some unique-looking code. This is how Node retrives
// parameters passed in from client requests. The url module
// handles all these functions. The parse function
// deconstructs the URL, and places the query key-values in the
// query object. We can find the value for the "number" key
// by referencing it directly - the beauty of JavaScript.
var params = url.parse(request.url, true).query;
var input = params.number;

// These are the generic JavaScript methods that will create
// our random number that gets passed back to the caller
var numInput = new Number(input);
var numOutput = new Number(Math.random() * numInput).toFixed(0);

// Write the random number to response
response.write(numOutput);

// Node requires us to explicitly end this connection. This is because
// Node allows you to keep a connection open and pass data back and forth,
// though that advanced topic isn't discussed in this article.
response.end();

// When we create the server, we have to explicitly connect the HTTP server to
// a port. Standard HTTP port is 80, so we'll connect it to that one.
}).listen(8081);

// Output a String to the console once the server starts up, letting us know everything
// starts up correctly
console.log("Random Number Generator Running...");


2. 在命令行中运行 node random.js
下面是服务器已经启动并运行时看起来的样子:
node random.js
Random Number Generator Running...
[quote]
你可能会遇到错误代码Error: listen EADDRINUSE
意思是:错误地址使用。‘EADDRINUSE’应该是‘error address in use’的缩写。后来借助google找到了合理的解释,说是你监听的端口已经被使用了!
如过你使用的是Linux,可能会使用如下命令:
sudo fuser -n tcp 80 //查询什么进程占用了80端口
sudo kill pid * //kill pid
[/quote]

3. 打开浏览器,输入地址http://localhost:8081/?number=27 你将看到返回的数字结果


参考:
https://github.com/joyent/node/wiki/modules //可用的模块
https://www.npmjs.org/ NPM是一个Node包管理和分发工具,已经成为了非官方的发布Node模块(包)的标准。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值