nodejs里写一个自定义的redis客户端

一. 什么是Node.js?

Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。Node.js 使用了一个事件驱动、非阻塞式 I/O 的模型,使其轻量又高效。

Node 是一个让 JavaScript 运行在服务端的开发平台,它让 JavaScript 成为与PHP、Python、Perl、Ruby 等服务端语言平起平坐的脚本语言。 发布于2009年5月,由Ryan Dahl开发,实质是对Chrome V8引擎进行了封装。

Node对一些特殊用例进行优化,提供替代的API,使得V8在非浏览器环境下运行得更好。V8引擎执行Javascript的速度非常快,性能非常好。 Node是一个基于Chrome JavaScript运行时建立的平台, 用于方便地搭建响应速度快、易于扩展的网络应用。Node 使用事件驱动, 非阻塞I/O 模型而得以轻量和高效,非常适合在分布式设备上运行数据密集型的实时应用。

官网上对其特点描述为:
  • 它是一个Javascript运行环境

  • 依赖于Chrome V8引擎进行代码解释

  • 事件驱动

  • 非阻塞I/O

  • 轻量、可伸缩,适于实时数据交互应用

  • 单进程,单线程

二. Node.js中模块化开发规范

Node.js规定一个JavaScript文件就是一个模块,模块内部定义的变量和函数默认情况下在外部无法得到。
模块内部可以使用exports对象进行成员导出, 使用require方法导入其他模块。

三. 自己写一个操作redis的client 模块。

首先我们需要安装nodejs环境

  • 首先我们要在nodejs中使用redis必须下载redis模块,在你的项目文件夹下执行下面命令
    1
    npm install redis

1. 准备配置文件

按习惯,我们先在项目文件夹下建一个文件夹modules再在这个文件夹下建一个文件夹redis
我希望把redis链接的相关信息写在一个配置文件而不是程序内,所以我首先创建一个redis的配置文件
文件名为config.json
config.json

1
2
3
4
5
6
7
8
{
"redis":{
"port":"6379",
"host":"localhost",
"password":"password",
"detect_buffers": "true"
}
}

2. 引入相关模块

开始写redisClient.js,
首先把redis插件和自定义的配置文件声明进来

1
2
const redis = require('redis')
const redisOptions = require('./config').redis

3. 从redisOptions文件中读取并配置redis options参数信息

然后设置redis配置信息,出了连接方式还有缓存设置以及重连机制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const options = {
host: redisOptions.host,
port: redisOptions.port,
password: redisOptions.pass,
detect_buffers: redisOptions.detect_buffers, // 传入buffer 返回也是buffer 否则会转换成String
retry_strategy: function (options) {
// 重连机制
if (options.error && options.error.code === "ECONNREFUSED") {
// End reconnecting on a specific error and flush all commands with
// a individual error
return new Error("The server refused the connection");
}
if (options.total_retry_time > 1000 * 60 * 60) {
// End reconnecting after a specific timeout and flush all commands
// with a individual error
return new Error("Retry time exhausted");
}
if (options.attempt > 10) {
// End reconnecting with built in error
return undefined;
}
// reconnect after
return Math.min(options.attempt * 100, 3000);
}
}

4. 定义模块方法

接下来我们根据设置好的参数创建一个redis客户端对象> 并且定义4个需要暴露在模块外使用的方法

  1. setValue //存储值
  2. getValue //读取String
  3. getHvalue //读取hash
  4. quit //退出
1
2
3
4
5
6
7
8
// 生成redis的client
const client = redis.createClient(options)

const setValue = ()=>{}
const getValue = ()=>{}
const getHValue = ()=>{}
const quit = ()=>{}

完善方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
 
// 存储值
const setValue = (key, value) => {
if (typeof value === 'string') {
client.set(key, value)
} else if (typeof value === 'object') {
for (let item in value) {
client.hmset(key, item, value[item],redis.print)
}
}
}

// 获取string
const getValue = (key) => {
return new Promise((resolve, reject) => {
client.get(key, (err, res) => {
if (err) {
reject(err)
}else{
resolve(res)
}
})
})
}

// 获取hash
const getHValue = (key) => {
return new Promise((resolve, reject) => {
client.hgetall(key, function (err, value) {
if (err) {
reject(err)
} else {
resolve(value)
}
})
})
}

const quit = () => {
client.quit();
}

5. 暴露出可以调用的方法

使用module.exports 将外部可调用方法暴露出来。

1
2
3
4
5
6
7
// 导出
module.exports = {
setValue,
getValue,
getHValue,
quit
}

四. 写个文件测试一下

testRedis.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const redis = require('./modules/redis/redisClient')

redis.setValue('student', {
name: 'xiaoming',
age: 18,
sex: 1
})

redis.setValue('book', 'yuwen')

redis.getValue('book').then(res => {
console.log(res)
}).catch(err => {
throw new Error(err)
})

redis.getHValue('student').then(res => {
console.log(res)
}).catch(err => {
throw new Error(err)
})

redis.quit();

output:

1
2
3
4
5
6
D:\workspace\redisClient>node testRedis.js
Reply: OK
Reply: OK
Reply: OK
yuwen
{ name: 'xiaoming', age: '18', sex: '1' }

成功了!!