首页 > 技术文章 > Nodejs基础之redis

xiaocongcong888 2018-10-22 21:11 原文

安装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)
})
1
2
3
4
5
6
7
设置和读取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)
})
1
2
3
4
5
6
7
8
9
10
11
list的出栈(删除)
const redis = require('redis')
const client = redis.createClient(6379, 'localhost')

client.lpop('testLists', function(e,v){
v // 被出栈的元素
}) // 从左边出栈
client.rpop('testLists', function(e,v){}) // 从右边出栈
1
2
3
4
5
6
7
集合的设置和读取(不会重复插入)
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)
})
1
2
3
4
5
6
7
8
9
发布和订阅
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)
})

作者:millions_02
来源:CSDN
原文:https://blog.csdn.net/millions_02/article/details/78950504
版权声明:本文为博主原创文章,转载请附上博文链接!

推荐阅读