本人最近在学习黄健宏老师的《Redis使用手册》,由于书中代码基于python,本人对python并不熟悉,故尝试以javascript代码重现之,加以巩固。
- 首先使用
node运行npm install -g redis@4.1命令安装node_redis,这里我安装的是4.1版本,package.json文件如下:
{
"name": "redis",
"version": "1.0.0",
"description": "redis",
"type": "module",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "niduoniyema",
"license": "ISC",
"dependencies": {
"redis": "4.1"
}
}
redis的windows版本安装下载略。- 创建
test.js文件引入redis并编写测试代码,代码如下:
import { createClient } from 'redis';
const client = createClient();
client.on('error', err => {
console.log('redis连接失败', err);
//这里需要断开连接,否则会自动重新连接导致错误刷屏
client.quit();
});
client.connect()
.then(() => console.log('redis连接成功'));
client.set('name', '张三');
const value = await client.get('name');
console.log('value是:', value);
- 不开启
redis服务器时运行node .\test.js,结果如下:
- 开启
redis服务器:
- 运行代码,正常运行: