node mysql2/promise的连接池如何释放连接?

使用mysql2/promise的连接池因为连接没有释放,最后mysql会报Can't create more than max_prepared_stmt_count statements错误,那么它如何释放连接呢?
我的代码是这样的
1.创建连接

const mysql = require('mysql2/promise')
 var connection =  mysql.createPool(mysqlConfig)
  global.connection = connection

2.把链接挂载到ctx上

app.use(async (ctx, next) => {

  ctx.mysqlConection = global.connection
  // console.log(global.connection, '99999999999')
  ctx.controller = controller
  ctx.service = service
  ctx.are = are
  ctx.iz = iz
  ctx.rules = rules.rules
  ctx.model = mongodb.mongoose.models;
  await next()
  ctx.mysqlConection.end()

})```

3. 在controller就可以使用连接
findUv: async function (ctx) {
    let condition = ctx.request.body
    let sql = `SELECT count AS uv FROM gugudai_count ORDER BY id ASC LIMIT 1`
    console.log('******************2',ctx.mysqlConection.getConnection)
 
    const [rows, fields] = await ctx.mysqlConection.execute(sql)
    // let conne=await ctx.mysqlConection.getConnection;
    // console.log(conne)
    return { rows }
},
阅读 6.2k
2 个回答

看完你的回复,看了下官网API,可能你的写法在其他包没问题,但不符合mysql2的实现。比如一开始链接并没有被创建,而是按需创建,并需要自己回收。

// For pool initialization, see above
pool.getConnection(function(conn) {
   // Do something with the connection
   conn.query(/* ... */);
   // Don't forget to release the connection when finished!
   pool.releaseConnection(conn);
})

mysql2

楼上的想法应该是并发的请求数。
1。用await等待下一个请求之前,还没有结束这一次链接。那么就存在多个请求使用单一mysql链接(这里是指全局变量)
2。单例模式给你的体验就是和全局变量差不多,但是实际上单例不同于变量,单例类始终占用同样内存地址,1号请求和2号请求同样是用一个单例类。
3。可以简单理解为,如果你是全局变量,那么1号请求在使用global进行select的时候,2号也要使用global进行select

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题