zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

Nodejs使用redis详解编程语言

RedisNodejs编程语言 使用 详解
2023-06-13 09:20:35 时间
client.set("key", "Hello World", function (err, reply) { console.log(reply.toString()); }); //使用get 获取key的值 client.get("key", function (err, reply) { console.log(reply.toString()); }); }

同时可用expire来设置对象失效时间

//设置key的失效时间 

client.expire(key, 3); 

下面是redis 实战完整代码,可供参考 

var redis = require("redis"),//召唤redis 

 连接redis数据库,createClient(port,host,options); 

 如果REDIS在本机,端口又是默认,直接写createClient()即可 

 redis.createClient() = redis.createClient(7788, 127.0.0.1, {}) 

client = redis.createClient(7788,192.168.159.128,{}); 

//如果需要验证,还要进行验证 

//client.auth(password, callback); 

// if youd 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(); 

 

11755.html

cjava