随笔 - 34  文章 - 0 评论 - 270 阅读 - 15万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

安装方法

安装redis方法请自行百度,

npm方法,安装nodejsredis模块

1
npm install redis  

实战

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var redis = require("redis") ,
client = redis.createClient();
 
client.on("error", function (err) {
    console.log("Error " + err);
});
   
//链接redis_name表
client.on("connect", redis_name);
  
  
function runSample() {
     //使用set 对key 进行赋值,
      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来设置对象失效时间

1
2
//设置key的失效时间
client.expire('key', 3);  

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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 you'd 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(); 
}); 

  

 

posted on   peiyu1988  阅读(437)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示