Node.js開發之訪問Redis資料庫教程_node.js

來源:互聯網
上載者:User

大家要記住,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寫入一個鍵/值,再根據鍵名讀出索引值。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.