NodeJS連線Redis實現增刪改查
阿新 • • 發佈:2019-01-07
redis的db庫可以設定
const redis = require('redis'); const client = redis.createClient(); song1={ "rank": 1, "songname": "沙漠駱駝", "songplayurl": "https://www.xiami.com/song/xNdNB3df465", "songid": "1796001263", "singer": "展展與羅羅", "songurl": "http://www.xiami.com/widget/xml-single/uid/0/sid/1796001263", 'albumsongs':[{'songname':'123','songurl':'www.123'},{'songname':'123','songurl':'www.123'},{'songname':'123','songurl':'www.123'}] } song2={ "rank": 10, "songname": "一百萬個可能", "songplayurl": "https://www.xiami.com/song/8GsZTDe5093", "songid": "1773650237", "singer": "Christine Welch(克麗絲叮)", "songurl": "http://www.xiami.com/widget/xml-single/uid/0/sid/1773650237" } data=[] data2=[1,2,3,4,5,'a','b','c'] data.push(JSON.stringify(song1)) data.push(JSON.stringify(song2)) console.log(data) console.log(data2) insertListInDB('test',data) insertListInDB('test2',data2) querylistdata('test') querylistdata('test2') getdbnamelist() deletelistdata('test') getdbnamelist() updatelist('test2',1,'test') //獲取當前db中所有的key function getdbnamelist(){ // 相當於命令(keys *), 返回list,包含當前db所有key的名字 client.keys('*',function(err,val){ console.log(val); //callback(val); }); } //新增list資料 function insertListInDB(dbname,dbdata){ client.lpush(dbname,dbdata, function (err) { if (err) { console.log(err); }else{ console.log('insert[%d] 個數據 in db[%s] finished',dbdata.length,dbname); } }); } //查詢指定的key中,指定位置的內容 function querylistdata(dbname){ //0 為起始位置,-1為最後的位置 client.lrange(dbname,0,-1,function(err,val){ if(err){ console.log(err); } else{ console.log('read data from DB success. data length=[%d]',val.length); console.log(val) } }); } //刪除 function deletelistdata(dbname){ //保留指定位置的內容,其他全部刪除,所以從0到-1就是一個不刪; 從-1到0就是資料全部刪除,相當於del key client.ltrim(dbname,-1,0,function(err,val){ console.log('delet all data in db[%s] ,finished val=[%s] ',dbname,val); }); } //更新指定位置內容 function updatelist(dbname,dbdataindex,newinfo){ client.lset(dbname,dbdataindex,newinfo,function(err,val){ console.log('update dbdataindex[%s] data.length=[%s],dbname=【%s】 finished val=[%s] ',dbdataindex,newinfo.length,dbname,val); }); }