[Redis]Node操作Redis


Node操作Redis請使用node_redis

node安裝方法 npm install redis

GitHub網址 https://github.com/NodeRedis/node_redis

 

使用說明

1. 連接Redis服務

var redis = require("redis");
// 使用createClient方式來連接服務器
var client = redis.createClient(6379, '127.0.0.1');

// 注冊事件,注意 ready 事件在 connect 事件前面
client.on("error", function(error){
    console.log("Error " + error);
    console.log("redis error");
});

client.on("ready", function(err){
    if(err){
        console.log("Error " + error);
    }else{
        console.log("redis ready");
    }
})

client.on("connect", function(err){
    if(err){
        console.log("Error " + error);
    }else{
        console.log("redis connect");
    }
})

client.on("reconnecting", function(err){
    if(err){
        console.log("Error " + error);
    }else{
        console.log("redis reconnecting");
    }
})

client.on("end", function(err){
    if(err){
        console.log("Error " + error);
    }else{
        console.log("redis end");
    }
})

client.on("warning", function(err){
    if(err){
        console.log("Error " + error);
    }else{
        console.log("redis warning");
    }
})

使用 redis.createClient(port, hostname) 方式來連接服務器

 

2. 操作Redis數據

簡單的string數據類型,使用 set 和 get

復雜的hash數據類型,使用 hmset 和 hget 和 hkeys

// 使用set進行string類型數據的設置
client.set("color", "red", redis.print);

// 使用get進行string類型數據的讀取
client.get("color", function(err, value){
    if(err) throw err;
    console.log("Got: " + value);
})
// 使用hmset進行hash數據類型的設置
client.hmset("camping", {
    shelter: '2-person tent',
    cooking: 'campstove'
}, redis.print);

// 使用hget讀取hash數據類型的某個指定key的值
client.hget("camping", 'cooking', function(err, value){
    if(err){
        throw err;
    }
    console.log("will be cooking with " + value);
})

// 使用hkeys進行hash數據類型的keys獲取
client.hkeys('camping', function(err, keys){
    if(err) throw err;
    keys.forEach(function(key, i){
        console.log("  " + key);
    });
});

鏈表數據類型的操作方法有 lpush 和 lrange

client.lpush("tasks", "Paint the bikeshed red.", redis.print);
client.lpush("tasks", "Paint the bikeshed green.", redis.print);
client.lpush("tasks", "Paint the bikeshed blue.", redis.print);
client.lrange("tasks", 0, -1, function(err, items){
    if(err){
        throw err;        
    }else{
        items.forEach(function(item, i){
            console.log("  "+item);
        });
    } 
});

 

無序集合set 的操作方法有  sadd 和  smembers

client.sadd("ip_address_set", '204.10.37.96', redis.print);
client.sadd("ip_address_set", '204.10.37.96', redis.print);
client.sadd("ip_address_set", '204.75.37.152', redis.print);
client.smembers("ip_address_set", function(err, members){
    if(err) throw err;
    console.log(members);
});

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM