Node.js开发之访问Redis数据库教程

大家要记住,Node.js主要用于构建高性能、高可伸缩性的服务器和客户端应用,它面向的是“实时Web”。
Node.js的目标是提供一个“以简单的方式构建可扩展的网络服务器”,它受到来自Ruby语言的事件机(Event Machine)和来自Python的Twisted框架的影响。

Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。从2010年3月15日起,Redis的开发工作由VMware主持。

1、安装Redis的Node.js驱动


ThinkPad:~/work$ mkdir redis-node

ThinkPad:~/work$ cd redis-node

ThinkPad:~/work/redis-node$ ls

ThinkPad:~/work/redis-node$ npm install redis

npm http GET https://registry.npmjs.org/redis

计算机卡在了这里,npm远程服务器连接十分缓慢,怎么办?

考虑使用NPM的国内镜像服务器。

有三种方法:

1)使用config命令


npm config set registry http://registry.cnpmjs.org

npm info underscore (如果上面配置正确这个命令会有字符串response)

2)命令行指定


npm --registry http://registry.cnpmjs.org info underscore

3)编辑 ~/.npmrc 加入以下内容:


registry = http://registry.cnpmjs.org

再次执行Redis驱动的安装:


ThinkPad:~/work/redis-node$ npm install redis

npm http GET http://registry.cnpmjs.org/redis

npm http 304 http://registry.cnpmjs.org/redis

redis@0.10.0 node_modules/redis

搞定!

2、编写测试程序


// redis-test.js

var redis = require("redis"),

    client = redis.createClient(6379, "10.3.30.186");

client.on("error", function(err){     console.log("Error: " + err); });

client.on("connect", function(){     // start server();     client.set("name_key", "hello world", function(err, reply){         console.log(reply.toString());     });

    client.get("name_key", function(err, reply){         console.log(reply.toString());     }); })

3、执行程序


ThinkPad:~/work/redis-node$ node redis-test.js

OK

hello world


程序说明:先连接远程Redis服务器,然后向Redis写入一个键/值,再根据键名读出键值。