如何在EC2环境中使用node-mongodb-native在Node.js服务器上设置MongoDB? [英] How can I set up MongoDB on a Node.js server using node-mongodb-native in an EC2 environment?

查看:59
本文介绍了如何在EC2环境中使用node-mongodb-native在Node.js服务器上设置MongoDB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从这里的很多人那里得到了帮助,现在我想回馈自己.对于那些无法使MongoDB使用Node.js服务器的人,这就是我所做的.

I got help from many people here, and now I want to contribute back. For those who are having trouble making a Node.js server work with MongoDB, here is what I've done.

推荐答案

这最初是由问问题者发布的.一个mod在评论中要求他将其发布为答案,但未得到任何回应.因此,我将其清理干净并亲自发布.

查看代码时,您会注意到createServer代码位于db.open内部.如果您将其撤消,它将无法正常工作.另外,请勿关闭数据库连接.否则,第一次之后,数据库连接将不会再次打开. (当然,db.open是在createServer之外声明的.)我不知道为什么createServerdb.open内部.我想这可能与不打开太多数据库连接有关?

When you look at the code, you will notice that the createServer code is inside db.open. It won't work if you reverse it. Also, do not close the db connection. Otherwise, after the first time, the db connection will not be opened again. (Of course, db.open is declared outside of createServer.) I have no clue why createServer is inside db.open. I guess it may have to do with not opening too many db connections?

另外,我面临的一个问题是,当我通过SSH运行它时,即使我在后台运行服务器(例如$ node server.js &),在2.5小时后,服务器也会死机(虽然不是实例).我不确定这是因为终端连接还是什么原因.

Also, one problem I face is that when I run it via SSH, even if I run the server in the background (e.g. $ node server.js &), after 2.5 hours, the server dies (not the instance though). I am not sure if it is because of terminal connection or what.

以下是步骤&代码

环境:EC2,AMS-Linux-AMI

Environment: EC2, AMS-Linux-AMI

目的:接收一个HTTP请求并将查询,IP和时间戳记录到MongoDB中.

Purpose: Take an HTTP request and log the query, IP and timestamp into MongoDB.

步骤

1)创建实例(服务器)后,安装gcc.

1) After creating the instance (server), install gcc.

$ yum install gcc-c++

2)下载Node.js文件并将其解压缩. (我使用的是2.6版.)

2) Download Node.js files and unzip them. (I used version 2.6.)

$ curl -O http://nodejs.org/dist/node-v0.2.6.tar.gz
$ tar -xzf node-v0.2.6.tar.gz

我将解压缩的文件夹重命名为"nodejs"

I renamed the unzipped folder to just "nodejs"

$ cd nodejs
$ sudo ./configure --without-ssl
$ sudo make
$ sudo make install

make需要一段时间....之后,您可以尝试在nodejs.org中运行示例

make takes a long while.... After that you can try running the sample in nodejs.org

3)安装MongoDB.我安装的版本是1.6.5,而不是1.7.

3) Install MongoDB. I installed version 1.6.5, not 1.7.

$ curl -O http://fastdl.mongodb.org/linux/mongodb-linux-x86_64-1.6.5.tgz
$ tar -xzf mongodb-linux-x86_64-1.6.5.tgz
$ sudo mkdir /data/db/r01/

我将文件夹重命名为"mongodb"

I renamed the folder to "mongodb"

运行数据库进程:

$ ./mongodb/bin/mongod --dbpath /data/db/r01/

然后,如果您愿意,可以运行并尝试命令行.请访问MongoDB的网站.

Then if you like, you can run and try out the command line. Refer to MongoDB's website.

4)我建议您根据实例创建自己的AIM.大约需要20分钟.然后,重新创建安装并再次运行MongoDB.

4) I recommend that you create your own AIM based on your instance. It will take 20 minutes. Then, recreate the install and run MongoDB again.

5)安装node-mongodb-native

$ curl -O https://download.github.com/christkv-node-mongodb-native-V0.8.1-91-g54525d8.tar.gz
$ tar -xzf christkv-node-mongodb-native-V0.8.1-91-g54525d8.tar.gz

我将文件夹重命名为node-mongodb-native

$ cd node-mongodb-native
$ make

6)这是服务器的代码:

6) Here is the code for the server:

GLOBAL.DEBUG = true;
global.inData = '';
var http = require('http');
sys = require("sys");

/* set up DB */

var Db = require('./node-mongodb-native/lib/mongodb').Db,
  Connection = require('./node-mongodb-native/lib/mongodb').Connection,
  Server = require('./node-mongodb-native/lib/mongodb').Server,
  BSON = require('./node-mongodb-native/lib/mongodb').BSONNative;

var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost';
var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT;
var db = new Db('test01', new Server(host, port, {}), {native_parser:true});

db.open(function(err, db) { 
    http.createServer(function (req, res) {
        res.writeHead(200, {'Content-Type': 'text/plain'});

        global.inData = {'p':'', 'url':''};

        // get IP address
        var ipAddress = req.connection.remoteAddress;
        global.inData.ip = ipAddress;

        // date time
        var d = new Date();
        var ts = d.valueOf();
        global.inData.ts = ts;

        // get the http query
        var qs = {};
        qs = require('url').parse(req.url, true);
        if (qs.query !== null) {
            for (var key in qs.query) {
                if (key == 'p') {
                    global.inData.p = qs.query[key];
                }
                if (key == 'url') {
                    global.inData.url = qs.query[key];
                }
            }
        }

        if (global.inData.p == '' && global.inData.url == '') {
            res.end("");
        } else {
            db.collection('clickCount', function(err, collection) { 
                if (err) {
                    console.log('is error \n' + err);
                }

                collection.insert({'p':global.inData.p, 
                  'url':global.inData.url,
                  'ip':global.inData.ip, 
                  'ts':global.inData.ts});
                res.end("");
                //db.close();  // DO NOT CLOSE THE CONNECTION
            }); 
        }
    }).listen(8080); 
});

console.log('Server running at whatever host :8080');

这可能不是完美代码,但它可以运行.我仍然不习惯使用嵌套"或LISP类型的编码样式.这就是为什么我作弊并使用global.inData传递数据的原因. :)

This may not be perfect code, but it runs. I'm still not used to the "nested" or LISP kind of coding style. That's why I cheated and used global.inData to pass data along. :)

不要忘记将res.end("")放在适当的位置(您认为HTTP请求调用应在此结束).

Don't forget to put res.end("") in the appropriate location (where you think the HTTP request call should be ended).

这篇关于如何在EC2环境中使用node-mongodb-native在Node.js服务器上设置MongoDB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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