转自 https://blog.csdn.net/millions_02/article/details/78950504
redis
安装redis 模块
npm install redis
1
代码部分
const redis = require('redis')
const client = redis.createClient(6379, 'localhost')
client.set('hello', {a:1, b:2}) // 注意,value会被转为字符串,所以存的时候要先把value 转为json字符串
client.get('hello', function(err, value){
console.log(value)
})
设置和读取list型数据结构(会重复插入)
const redis = require('redis')
const client = redis.createClient(6379, 'localhost')
client.rpush('testLists', 'a') // 从右边插入
client.rpush('testLists', 'b')
client.rpush('testLists', 'b')
client.lpush('testLists', '1')// 从左边插入
// 读取 0:开头 -1:结尾
client.lrange('testLists', 0, -1, function(err,lists){
console.log(lists)
})
list的出栈(删除)
const redis = require('redis')
const client = redis.createClient(6379, 'localhost')
client.lpop('testLists', function(e,v){
v // 被出栈的元素
}) // 从左边出栈
client.rpop('testLists', function(e,v){}) // 从右边出栈
集合的设置和读取(不会重复插入)
const redis = require('redis')
const client = redis.createClient(6379, 'localhost')
// 设置
client.sadd('testSet', 1})
client.sadd('testSet', 2})
// 读取
client.smentbers('testSet', function(e,v){
console.log(v)
})
发布和订阅
const redis = require('redis')
const client = redis.createClient(6379, 'localhost')
// 发布
client.publish('testPublish', 'message form testPublish')
// 订阅
client.subscribe('testPublish')
// 监听消息
client.on('message', function(channel,msg){
console.log(channel + ':' + msg)
})