在CloudFoundry 中使用MongoDB、Node.js构建应用

2011-06-17 18:50

在CloudFoundry 中使用MongoDB、Node.js构建应用

by nosqlfan

at 2011-06-17 10:50:34

original http://item.feedsky.com/~feedsky/nosqlfan/~8149226/524010759/6253001/1/item.html

CloudFoundryVMware公司前段时间发布的云计算平台,NoSQL存储MongoDB和Redis都在上面有很好的支持,下面是一篇10gen官方博客中的文章,算是一篇在CloudFoundry平台中使用MongoDB和Node.js 搭建应用的入门教程,步骤详尽,描述清楚,如果你对云平台感兴趣,不妨一看。

1.工欲善其事

第一步当然是在平台上注册并安装各种工具了,按照教程中的指导,先完成环境搭建

  1. Sign up for a Cloud Foundry account.
  2. Local installation of MongoDBNode.JS.
  3. Cloud Foundry VMC tools.
  4. All of the code is available on github.

在本地启动一个MongoDB,这样你就能在本地时用本地的MongoDB,在上传代码后用云服务中的MongoDB了。

2.vmc登录

mongo@ubuntu:~$ sudo gem install vmc
mongo@ubuntu:~$ vmc target api.cloudfoundry.com
Succesfully targeted to [http://api.cloudfoundry.com]

mongo@ubuntu:~$ vmc login
Email: gates@10gen.com
Password: ********
Successfully logged into [http://api.cloudfoundry.com]

3.Hello World程序

创建一个叫app.js的程序,输入如下代码,这段代码会在localhost:3000端口上启动一个输出“Hello World”字样的HTTP服务。

var port = (process.env.VMC_APP_PORT || 3000);
var host = (process.env.VCAP_APP_HOST || 'localhost');
var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(port, host);

在本地命令行下测试:

$ node app.js
$ curl localhost:3000
Hello World
# kill node with CTRL+C

好,没有问题,那么将代码部署到云服务,使用vmc的push方法:

$ vmc push
Would you like to deploy from the current directory? [Yn]: Y
Application Name: gvp_node_test
Application Deployed URL: 'gvp_node_test.cloudfoundry.com'?
Detected a Node.js Application, is this correct? [Yn]: Y
Memory Reservation [Default:64M] (64M, 128M, 256M, 512M, 1G or 2G)
Creating Application: OK
Would you like to bind any services to 'gvp_node_test'? [yN]: y
The following system services are available::
1. mongodb
2. mysql
3. redis
Please select one you wish to provision: 1
Specify the name of the service [mongodb-55516]:
Creating Service: OK
Binding Service: OK
Uploading Application:
  Checking for available resources: OK
  Packing application: OK
  Uploading (0K): OK
Push Status: OK
Staging Application: OK
Starting Application: OK

现在你使用curl命令就能在平台上测试你的服务了

$ curl your_app_name.cloudfoundry.com
Hello World

4.用MongoDB记录客户端信息

下一步开始配置MongoDB,先加入下面代码,这个if else判断是因为在本地和云端都需要测试,用于区分不同的环境。

if(process.env.VCAP_SERVICES){
  var env = JSON.parse(process.env.VCAP_SERVICES);
  var mongo = env['mongodb-1.8'][0]['credentials'];
}
else{
  var mongo = {"hostname":"localhost","port":27017,"username":"",
    "password":"","name":"","db":"db"}
}

再加入一个将配置转成MongoDB url的形式即可。代码请看这里

然后将刚刚更新的内容同步到平台,运行如下命令:

$ vmc update your_app_name
Uploading Application:
...
Stopping Application: OK
Staging Application: OK
Starting Application: OK
# test again
$ curl your_app_name.cloudfoundry.com
# bunch of environment variables

然后安装node.js的mongodb扩展

$ npm install mongodb

奖安装好的扩展包含进来,然后将具体的HTTP处理脚本改成如下的方式,这个功能是将IP和访问时间记录到MongoDB中

var record_visit = function(req, res){
  /* Connect to the DB and auth */
  require('mongodb').connect(mongourl, function(err, conn){
    conn.collection('ips', function(err, coll){
      /* Simple object to insert: ip address and date */
      object_to_insert = { 'ip': req.connection.remoteAddress, 'ts': new Date() };

      /* Insert the object then print in response */
      /* Note the _id has been created */
      coll.insert( object_to_insert, {safe:true}, function(err){
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.write(JSON.stringify(object_to_insert));
        res.end('\n');
      });
    });
  });
}

再启动服务,访问两次,应该能在你的mongodb里找到对应的记录

http.createServer(function (req, res) {
  record_visit(req, res);
}).listen(port, host);

这里可以看到这一步的代码

5.获取MongoDB中的访问记录

我们记录了登录IP和时间,下面再增加一个功能,获取IP和时间,添加如下函数

var print_visits = function(req, res){
  /* Connect to the DB and auth */
  require('mongodb').connect(mongourl, function(err, conn){
    conn.collection('ips', function(err, coll){
      /*find with limit:10 & sort */
      coll.find({}, {limit:10, sort:[['_id','desc']]}, function(err, cursor){
        cursor.toArray(function(err, items){
          res.writeHead(200, {'Content-Type': 'text/plain'});
          for(i=0; i < items.length; i++){
            res.write(JSON.stringify(items[i]) + "\n");
          }
          res.end();
        });
      });
    });
  });
}

然后修改httpserver相关的nodejs代码,使其支持一个/history的访问,返回最近的十条访问记录:

http.createServer(function (req, res) {
  params = require('url').parse(req.url);
  if(params.pathname === '/history') {
    print_visits(req, res);
  }
  else{
    record_visit(req, res);
  }
}).listen(port, host);

代码可以在这里看到。然后再把修改的代码部署上去进行测试,可以看到如下输出。

$ vmc update your_app_name
...
$ curl your_app_name.cloudfoundry.com
{"ip":"172.30.49.42","ts":"2011-06-15T20:14:18.977Z","_id":"4df9129af354f8682d000001"}
$ curl your_app_name.cloudfoundry.com
{"ip":"172.30.49.43","ts":"2011-06-15T20:14:21.745Z","_id":"4df9129df354f8682d000002"}

# now let's test history
$ curl gvp_node_test.cloudfoundry.com/history
{"ip":"172.30.49.43","ts":"2011-06-15T20:14:21.745Z","_id":"4df9129df354f8682d000002"}
{"ip":"172.30.49.42","ts":"2011-06-15T20:14:18.977Z","_id":"4df9129af354f8682d000001"}
...

6.更多

  1. 关注 Node.js Panel Discussion webinar.
  2. 还有下面一些MongoDB的node客户端封装
    • Mongoose, an ORM / ODM wrapper
    • MongoSkin, a layer over node-mongodb-native to help reduce callbacks.
  3. 还可以用 Express framework 框架建立更复杂的web应用

原文链接:Getting started with VMware CloudFoundry, MongoDB and Node.js

觉得文章还不错?快分享给更多的人吧!

您可能还喜欢:

在 VMware CloudFoundry 平台上构建 MongoDB + Rails 应用

*nix、node.js、MongoDB 下一代的LAMP

VMware构建云平台,MongoDB成核心存储服务

Instagram的实时图片Demo:Node.js, Redis 加 Web Sockets

使用Node.Js 操作 Riak
无觅