Nodejs 连接 Redis数据库实例

JavaScript07

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数据库的方法。分享给大家供大家参考,具体如下:

var

mysql

=

require('mysql')

//调用MySQL模块

mysql模块要安装

$

npm

install

mysql

//创建一个connection

var

connection

=

mysql.createConnection({

host

:

'127.0.0.1',

//主机

user

:

'root',

//MySQL认证用户名

password

:

'',

//MySQL认证用户密码

port:

'3306',

//端口号

database:''

//数据库名

})

//创建一个connection

connection.connect(function(err){

if(err){

console.log('[query]

-

:'+err)

return

}

console.log('[connection

connect]

succeed!')

})

//执行SQL语句

connection.query('SELECT

1

+

1

AS

solution',

function(err,

rows,

fields)

{

if

(err)

{

console.log('[query]

-

:'+err)

return

}

console.log('The

solution

is:

',

rows[0].solution)

})

//关闭connection

connection.end(function(err){

if(err){

return

}

console.log('[connection

end]

succeed!')

})

注:nodejs在操作数据库的时候不用设置数据库的编码格式

set

names

utf8

希望本文所述对大家nodejs程序设计有所帮助。

您可能感兴趣的文章:nodejs连接mysql数据库简单封装示例-mysql模块nodejs进阶(6)—连接MySQL数据库示例nodejs实现的连接MySQL数据库功能示例Nodejs连接mysql并实现增、删、改、查操作的方法详解nodeJs实现基于连接池连接mysql的方法示例nodejs中操作mysql数据库示例NodeJS链接MySql数据库的操作方法Nodejs使用mysql模块之获得更新和删除影响的行数的方法NodeJs使用Mysql模块实现事务处理实例nodejs连接mysql数据库及基本知识点详解