nodejs 下使用redis (安裝)

服務端語言:nodeJs;javascript

開始使用redis的時候碰到一些錯誤,找了一個小時最後才發現,沒有安裝redis服務器html

安裝redis

一、安裝redis服務器。這個能夠去菜鳥教程找連接:http://www.runoob.com/redis/redis-install.html;java

二、安裝redis模塊。npm install redis;node

測試連接redis

一、啓動redis。打開cmd,找到安裝redis的文件夾,輸入redis-server;git

二、nodejs客戶端連接redis-server。github

const    _redis = require("redis");//引入redis   
/*       注意:若是redis-server與nodejs客戶端都在本地,下列可寫成
 *       client = _redis.createClient();不然要對括號內容進行更改 */
const    client = _redis.createClient(6379,'127.0.0.1');//括號內容對應:(端口號,主機) 
client.on("ready", function (err) {  
    console.log("ready :" , "yes"); //連接成功檢測
}); 
client.on("error", function (err) {  
    console.log("Error :" , err);  //錯誤檢測
});

三、保存運行。若是打印出 ready : yes,則成功;redis

使用redis存取值

const 	redis = (function(){
//	添加string類型的數據 
//	@param  _key 鍵 
//	@params value 值  
//	@params expire (過時時間,單位秒;爲空表示不過時) 
//	@param  callBack(err,result)
	var mod ={};
	mod.set = function(_key, value, expire, callback){  
	    client.set(_key, value, function(err, result){  
	        if (err) {  
	            console.log(err);  
	            callback(err,null);  
	            return;  
	        }  
	        if (!isNaN(expire) && expire > 0) {  
	            client.expire(_key, parseInt(expire));  
	        }  
	  		callback(result);  
	    }) 
	}; 
	mod.get = function(_key, callback){  
	    client.get(_key, function(err,result){  
	        if (err) {  
	            console.log(err);  
	            callback(err,null)  
	            return;  
	        }  
	  		callback(result); 
	    })  
	};
	return mod     
})()
redis.set("swim","2012039210213",new Date().getTime(),function(result){
	console.log(result)//存入的狀態,正常則爲 "OK"
})
redis.get("swim",function(result){
	console.log(result)//取出的值
})

網上都是瞎扯淡,只有權威值得相信:https://github.com/NodeRedis/node_redisnpm

相關文章
相關標籤/搜索