Nodejs 连接 Redis数据库实例

Nodejs 连接 Redis数据库实例,第1张

报错:Node连接Redis报错 “ClientClosedError: The client is closed”

查询资料才发现:Node Redis版本V4之后,连接语法变了。

Starting from v4 of node-redis library, you need to call client.connect() after initializing a client. See this migration guide.

新语法:

const redis = require('redis')

const client = redis.createClient({ socket: { port: 6379 } })

client.connect()

client.on('connect', () =>{

    console.log('connected')

})

You might also want to consider running the client connect method with await in an asynchronous function. So you don't have to worry about event listeners.

const redis = require('redis')

(async () =>{

  try {

    const client = redis.createClient({ socket: { port: 6379 } })

    await client.connect()

    console.log('connected')

  } catch (err) {

    console.error(err)

  }

})()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

[Example]:

const redis = require("redis")

(async () =>{

  try {

    const client = redis.createClient({

      socket: { port: 6379 },

      legacyMode: true,

    })

    await client.connect()

    console.log("connected")

    await client.v4.set("key4", "value2", {

      NX: true,

    })

    client.set("key3", "value3", "NX", (err, reply) =>{})

    await client.get("key4", function (err, v) {

      console.log("redis get hello err,v", err, v)

    })

    client.set("student1", "Laylaa1", function (err, reply) {

      if (err) {

        console.log(err)

        callback(err, null)

        return

      }

      console.log(reply)

    })

  } catch (err) {

    console.error(err)

  }

})()

安装redis模块, 该模块会默认安装至当前目录下的node_modules里边:

npm install redis

然后连接redis, 并进行get-set *** 作

var redis = require('redis')

var client = redis.createClient('6379', '127.0.0.1')

// redis 链接错误

client.on("error", function(error) {

console.log(error)

})


欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/sjk/9937851.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-03
下一篇 2023-05-03

发表评论

登录后才能评论

评论列表(0条)

保存