[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);
});
复制代码
原文地址:https://www.cnblogs.com/shaozhu520/p/10906563.html