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)

  }

})()

// mysqlTest.js

//加载mysql Module

var Client = require(‘mysql').Client,

client = new Client(),

//要创建的数据库

TEST_DATABASE = ‘nodejs_mysql_test',

//要创建的表名

TEST_TABLE = ‘test'

//用户名

client.user = ‘root'

//密码

client.password = ‘root'

//创建连接

client.connect()

client.query(‘CREATE DATABASE ‘+TEST_DATABASE, function(err) {

if (err &&err.number != Client.ERROR_DB_CREATE_EXISTS) {

throw err

}

})

// If no callback is provided, any errors will be emitted as `'error'`

// events by the client

client.query(‘USE ‘+TEST_DATABASE)

client.query(

‘CREATE TABLE ‘+TEST_TABLE+

‘(id INT(11) AUTO_INCREMENT, ‘+

‘title VARCHAR(255), ‘+

‘text TEXT, ‘+

‘created DATETIME, ‘+

‘PRIMARY KEY (id))'

)

client.query(

‘INSERT INTO ‘+TEST_TABLE+' ‘+

‘SET title = ?, text = ?, created = ?',

['super cool', 'this is a nice text', '2010-08-16 10:00:23']

)

var query = client.query(

‘INSERT INTO ‘+TEST_TABLE+' ‘+

‘SET title = ?, text = ?, created = ?',

['another entry', 'because 2 entries make a better test', '2010-08-16 12:42:15']

)

client.query(

‘SELECT * FROM ‘+TEST_TABLE,

function selectCb(err, results, fields) {

if (err) {

throw err

}

console.log(results)

console.log(fields)

client.end()

}

)


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

原文地址: http://outofmemory.cn/sjk/9911061.html

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

发表评论

登录后才能评论

评论列表(0条)

保存