Nodejs 连接 Redis数据库实例

JavaScript010

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)

  }

})()

在java下可以使用 :

String value = redis.get(key)

是同步的

但在nodejs 下使用:

```javascript

var value

var isConnection = client.get(key,function(err,repy){

value = repy

client.quit()//调用了quit之后isConnection就是false了,这个get方法应该是返回连接状态吧?

})

client.get直接返回的结果是!client.shou_buffer。而且对于异步操作的js,这个值肯定是它向redis发送请求之前就被返回了的。