微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Node.js连接redis显示ClientClosedError错误的解决方法

问题调用redis的lpush函数显示lpush is not a function

在这里插入图片描述

代码如下:

const redis = require('redis');
const db = redis.createClient();

class Entry {
...
  save(cb) {
    const entryJSON = JSON.stringify(this);
    db.lpush(
      'entries',
      entryJSON,
      (err) => {
        if (err) return cb(err);
        cb();
      }
    );
  }
...
}

module.exports = Entry;

调试代码显示,当运行到lpush方法时,抛出ClientClosedError: The client is closed

在这里插入图片描述

原因:npm install认安装的Redis client for Node.js为V4.0.0版本,一些接口已经改变。
详见官方文档:v3 to v4 Migration Guide

解决方法

1.回退到node-redis v3.1.2

npm uninstall redis --save
npm install redis@3.1.2 --save

代码成功运行。

2.使用ioredis

const redis = require("ioredis");
const client = new redis();

代码成功运行。

3.尝试使用V4添加{legacyMode: true}参数,依旧报错。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐