node-redis 存取字符串、哈希、列表、集合、有序集合
2019-01-24 本文已影响0人
我的昵称好听吗
通过redis模块在node中连接到redis数据库: https://www.npmjs.com/package/redis
字符串
/**
* redis string
* 字符串
*/
const redisClient = require('../middlewares/redis');
module.exports = function (){
redisClient.set('mystring','one');
redisClient.get('mystring',function (err,replay){
if (err) {
console.log(err);
}
console.log(replay); // one
});
};
哈希
/**
* redis hash
* 哈希
*/
const redisClient = require('../middlewares/redis');
module.exports = function (){
redisClient.hmset("userInfo", {"name": null, "sex":null},function (err, res) {
if (err) {
console.log(err);
} else {
console.log(res);
}
});
redisClient.hset("userInfo", "name", "xiaohua");
redisClient.hget("userInfo", "name",(err,replies)=>{
if (err) {
logger.error(err);
} else {
console.log(replies);
}
});
redisClient.hgetall("userInfo", function (err, obj) {
console.log(obj);
});
redisClient.hdel('userInfo','name');
redisClient.hgetall("userInfo", function (err, obj) {
console.log(obj);
});
};
列表
/**
* redis list
* 列表
* 创建列表或者插入一个或多个数据:RPUSH key value [value ...]
* 设置列表指定位置值:LSET key index value
* 获取列表长度:LLEN key
* 获取指定范围列表值:LRANGE key start stop
*/
const redisClient = require('../middlewares/redis');
module.exports = function (){
redisClient.rpush('mylist',"one");
redisClient.lset('mylist',0,'two');
redisClient.llen('mylist',function (err,length){
if (err) {
console.log(err);
} else {
redisClient.LRANGE('mylist',0,length,function (err,replay){
if (err) {
console.log(err);
}
console.log(replay); // [ 'two', 'one', 'one', 'one', 'one' ]
});
}
});
};
集合
/**
* redis set
* 集合
* 在指定key的集合中添加一个或者多个元素(重复元素只能设置一个): SADD key member [member ...]
* key对应的集合中的元素数量:SCARD key
* 返回key集合所有元素: SMEMBERS key
*/
const redisClient = require('../middlewares/redis');
module.exports = function (){
redisClient.sadd('myset',"one");
redisClient.sadd('myset',"two");
redisClient.scard('myset',function (err,replay){
if (err) {
console.log(err);
} else {
console.log(replay); //2
}
});
redisClient.smembers('myset',function (err,replay){
if (err) {
console.log(err);
} else {
console.log(replay); //[ 'one', 'two' ]
}
});
};
有序集合
/**
* redis sorted set
* 有序集合
* 将所有指定成员添加到键为key有序集合(sorted set)里面: ZADD key [NX|XX] [CH] [INCR] score member [score member ...]
* key对应有序集合中元素的数量:ZCARD key
* 返回key对应有序集合中指定范围的元素:ZRANGE key start stop [WITHSCORES]
*/
const redisClient = require('../middlewares/redis');
module.exports = function (){
redisClient.zadd('myzset',0,"one");
redisClient.zadd('myzset',1,"one-");
redisClient.zadd('myzset',2,"one1");
redisClient.zcard('myzset',function (err,lenght){
if (err) {
console.log(err);
} else {
redisClient.zrange('myzset',0,lenght,'WITHSCORES',function (err,replay){
if (err) {
console.log(err);
} else {
console.log(replay); // [ 'one','0','one-','1','one1','2'] | [ 'one','one-',one1']
}
});
}
});
};