node.js中 redis 的安装和基本操作示例

来自:互联网
时间:2020-05-27
阅读:

本文实例讲述了node.js中 redis 的安装和基本操作。分享给大家供大家参考,具体如下:

一、win下安装redis

https://github.com/MicrosoftArchive/redis/releases

下载Redis-x64-3.2.100.zip,然后解压,放到自定义目录。

然后打开命令行工具,进入到该目录下,运行安装redis服务。

redis-server.exe --service-install redis.windows-service.conf --loglevel verbose

然后就可以启动redis服务了

redis-server --service-start

二、redis可视化工具RedisDesktopManager

https://github.com/uglide/RedisDesktopManager/releases

现在已经不免费了,可以下载早期版本。

三、redis的数据类型

1、字符串,最基本的类型,一个key对应一个value。

//设置值
set name xiaoxu
//获取值
get name
//获取子字符串,包含开始和结束索引的字符
getrange name 0 -1
getrange name 1 3
//自增加1
set age 1
incr age
//指定增加的数量
incrby age 5
//递减1
decr age
//指定递减的数量
decrby age 3
//删除指定的键
del age
//判断键是否存在
exists name
//设置过期时间,单位秒
expire name 10
//查看剩余生存时间
ttl name
//获取键的值类型
type name

2、哈希值,是一个键值对的集合,一个字符串类型的field和value的映射表,适合存储对象

//设置单个值
hset person name xiao
//设置多个值
hmset person age 24 height 172
//获取单个值
hget person name
//获取多个值
hmget person age height
//获取所有值
hgetall person
//删除键
hdel person name
//获取所有的键
hkeys person

3、列表,简单的字符串列表,按插入顺序排序。

//往列表左边插入
lpush list 1
lpush list 2
//往列表右边插入
rpush list 3
rpush list 4
//查看列表元素
lrange list 0 -1
//弹出元素
lpop list
rpop list
//通过索引获取元素
lindex list 1
//获取列表的长度
llen list
//删除列表的元素
//lrem key count value
// count > 0时,从表头开始搜索,删除与value相等的元素,数量为count
// count < 0时,从表尾开始搜索,删除与value相等的元素,数量为count绝对值
// count = 0时,删除列表中所有与value相等的元素
lrem list 1 1
lrem list -1 2

4、集合,是字符串类型的无序集合

//添加元素
sadd label 1 2 3
//查看集合
smembers label
//获取集合个数
scard label
//删除元素
srem label 2
//交集
sadd a 1 2 3
sadd b 2 3 4
sinter a b
//差集
sdiff a b
//并集
sunion a b

5、有序集合,跟集合一样也是字符串的集合,不过每个元素会关联一个double类型的分数,redis通过该分数给集合中的元素进行从小到大的排序。

//添加有序成员
zadd xiaoxu 60 math 77 english 80 chinaese
//获取有序成员数量
zcard xiaoxu
//查看有序集合
zrange xiaoxu 0 -1
//查看有序集合,显示分数
zrange xiaoxu 0 -1 withscores
//删除有序集合中的成员
zrem xiaoxu math

四、node.js中使用redis

安装redis库

npm install redis --save

操作redis的方法与我们在命令行中输入的命令基本一致

const redis = require('redis');
//创建一个redis客户端
let client = redis.createClient(6379, '127.0.0.1');
//操作redis基本跟在命令行操作一致
client.set('name', 'xiaoxu', function (err, result) {
  if (err) {
    console.log(err);
  }
  console.log(result);
});
client.hmset('person', 'name', 'xiaoxu', 'age', '25', function (err, result) {
  if (err) {
    console.log(err);
  }
  console.log(result);
});
client.hmget('person', 'name', 'age', function (err, result) {
  if (err) {
    console.log(err);
  }
  console.log(result);
});
client.hkeys('person', function (err, result) {
  if (err) {
    console.log(err);
  }
  result.forEach(function (value) {
    client.hget('person', value, function (err, result) {
      console.log(value, result);
    });
  });
  //退出
  client.quit();
});

通过bluebird来包装redis,让它支持async,await的方式,解决多层嵌套问题。

const redis = require('redis');
const bluebird = require('bluebird');
//通过bluebird包装
bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);
//创建一个redis客户端
let client = redis.createClient(6379, '127.0.0.1');
(async function () {
  //方法名后面都加上Async
  let result = await client.setAsync('name', 'hehe');
  console.log(result);
  result = await client.hmsetAsync('person', 'name', 'xiaoxu', 'age', '25');
  console.log(result);
  result = await client.hkeysAsync('person');
  console.log(result);
  result.forEach(async function (value) {
    let v = await client.hgetAsync('person', value);
    console.log(value, v);
  });
  client.quit();
})();

五、redis发布与订阅

redis发布订阅是一种消息通信模式,发送者发送消息,订阅者接收消息。

const redis = require('redis');
let clientA = redis.createClient(6379, '127.0.0.1');
let clientB = redis.createClient(6379, '127.0.0.1');
//客户端A订阅频道
clientA.subscribe('news');
clientA.subscribe('sports');
//客户端A监听消息
clientA.on('message', function (channel, message) {
  console.log('客户端A收到', channel, message);
  //客户端A在10秒后取消订阅
  setTimeout(function () {
    clientA.unsubscribe('news');
  }, 10000);
});
setInterval(function () {
  clientB.publish('news', '这是一条新闻' + new Date().toLocaleString());
  clientB.publish('sports', '这是一条体育' + new Date().toLocaleString());
}, 1000);

六、redis事务

redis事务可以一次性执行多个命令,multi 命令之后,exec命令之前,命令都会放到队列中,直到执行exec,将会执行队列中的命令。

discard可以取消事务,放弃执行事务块内的所有命令。

const redis = require('redis');
let client = redis.createClient(6379, '127.0.0.1');
client.multi()
.hset('person', 'name', 'haohao')
.hset('person', 'age', '34')
.exec(function (err, result) {
  if (err) {
    console.log(err);
  }
  console.log(result);
  client.quit();
});

注意redis中的事务跟mysql中的事务是有区别的。

希望本文所述对大家node.js程序设计有所帮助。

返回顶部
顶部