2012年7月1日 星期日

在 Ubuntu 12.04 安裝 redis 資料庫及node.js使用範例

在terminal 中執行以下命令即會安裝並啟動完成
$ sudo apt-get install redis-server

使用 npm 安裝 redis 提供 node.js 用的 module
$ npm install redis
$ npm install hiredis redis

測試 redis 是否運行順利:

1. 在node.js之工作目錄增加一檔案 app.js 並輸入以下內容:
var redis = require("redis"),
    client = redis.createClient();

client.on("error", function (err) {
    console.log("Error " + err);
});
// Set a value
client.set("string key", "Hello World", redis.print);
// Get the value back
client.get("string key", function (err, reply) {
    console.log(reply.toString());
});
// Clean quit (waits for client to finish)
client.quit();

2. 用 node.js 執行 app.js
$ node app.js
$ Reply: OK
$ Hello World


3. 在terminal中用命令列執行
$ redis-cli
redis 127.0.0.1:6379>
4. 停止 redis 之運行
$ src/redis-cli shutdown

5. 啟動 redis
$ src/redis-server

沒有留言:

張貼留言