Nodejs 连接 Redis数据库实例

JavaScript018

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)

  }

})()

NodeJS对mysql数据库的简单操作

1.

打开软件新建一个空的文件夹

2.

然后引入mysql依赖 npm install mysql 1 完成后对应文件夹下会生成一个node_modules的文件夹,我们不需要去管它

3.

编写mysql.js文件 // 导入mysql依赖constmysql=require("mysql")// 获取