Redis支持五种数据类型:string(字符串),hash(哈希),list(列表),set(集合)及zset(sorted set:有序集合)。
1.先npm install redis
2.新建redis.js,引入redis
var redis = require('redis');
var client = redis.createClient(6379,'127.0.0.1');
module.exports = client;
字符串操作
var client = require('./client')
client.set('hello','this is hello')
client.get('hello',(err,v)=>{
console.log(err,v)
})
Hash操作
var client = require('./client')
client.hset("hash","today","fine",function(err,response){
console.log(err,response);
});
client.hset("hash","tomorow","notfine",function(err,response){
console.log(err,response);
});
client.hget("hash","today",function(err,response){
console.log(err,response);
});
client.hgetall("hash",function(err,response){
console.log(err,response);
});
列表操作
假设文件名为list.js,重复执行Node list.js命令,会重复向testLists内插入a,b,c。这是列表和集合的区别之一。
var client = require('./client')
client.rpush('testLists', 'a'); //尾(右边)部插入
client.rpush('testLists', 'b');
client.lpush('testLists', 'c'); //头(左边)部插入
client.lpop('testLists', (err,list)=>{ //左边弹出(删除)
console.log(err,list)
});
client.rpop('testLists', (err,list)=>{ //右边弹出(删除)
console.log(err,list)
});
client.lrange('testLists', 0, -1,(err,list)=>{ //输入testLists变量,0和-1是下标,代表全部内容
console.log(err,list)
});
集合操作
如果testSet内部已经有1,2,3,重复执行此文件不会重复插入。
var client = require('./client')
client.sadd('testSet',1)
client.sadd('testSet',2)
client.sadd('testSet',3)
client.smembers('testSet', (err, v)=>{
console.log(err, v)
})
消息订阅
新建推送文件pub.js
var client = require('./client')
client.publish('testPublish', 'message form pub.js')
新建订阅文件sub.js
订阅testPublish频道,使用on()方法监听message
var client = require('./client')
client.subscribe('testPublish');
client.on('message', (channel, msg)=>{
console.log(channel, msg)
})
先执行node sub.js执行订阅操作
再执行node pub.js推送消息message form pub.js,
就可以在sub,js的输入栏中看到打印:
testPublish message form pub.js
网友评论