node.js應用Redis初步
阿新 • • 發佈:2019-02-19
node.js下使用Redis,首先:
1、有一臺安裝了Redis的伺服器,當然,安裝在本機也行
2、本機,也就是客戶端,要裝node.js
3、專案要安裝nodejs_redis模組
注意第 3 點,不是在本機安裝就行了,而是說,要在專案中安裝(引用)。
方法是,DOS視窗,在專案目錄下,輸入
npm install redis
這樣就將nodejs_redis下載一份,放到當前目錄下了。看看,多了一個資料夾:node_modules\redis
編寫以下程式碼,儲存到當前目錄下\hello.js
var redis = require("redis"),//召喚redis /* 連線redis資料庫,createClient(port,host,options); 如果REDIS在本機,埠又是預設,直接寫createClient()即可 redis.createClient() = redis.createClient(6379, '127.0.0.1', {}) */ client = redis.createClient(6379,'192.168.159.128',{}); //如果需要驗證,還要進行驗證 //client.auth(password, callback); // if you'd like to select database 3, instead of 0 (default), call // client.select(3, function() { /* ... */ }); //錯誤監聽? client.on("error", function (err) { console.log("Error " + err); }); client.set("string key", "string val", redis.print);//set "string key" "string val" /* redis.print,回撥函式,將redis的返回值顯示出來。上一句執行結果,將返回“OK” */ client.hset("hash key", "hashtest 1", "some value", redis.print); client.hset(["hash key", "hashtest 2", "some other value"], redis.print); //遍歷雜湊表"hash key" client.hkeys("hash key", function (err, replies) { console.log(replies.length + " replies:"); replies.forEach(function (reply, i) { console.log(" " + i + ": " + reply); }); client.hget("hash key","hashtest 1",redis.print); /*兩種都可以斷掉與redis的連線, end()很粗暴,不管3721,一下子退出來了,上面那句獲取雜湊表"hash key"的某個元素值的表示式將沒有結果返回 而quit()則是先將語句處理完畢再幹淨地退出,斯文得很 */ //client.end(); client.quit(); });
執行:
DOS視窗,當前專案目錄下,輸入
node hello.js
參考資料:英文的,但沒辦法,這裡最權威,最全面,其他地方查了查,感覺都是扯淡。