Perfect/Swift mySQL 每个请求必须有一个数据库连接吗?

With Perfect/Swift mySQL Must You Have a Single Database Connection Per Request?

对于 Perfect/mySQL (https://github.com/PerfectlySoft/Perfect-MySQL),我看到的示例表明您不能在多个连接之间重用单个数据库连接。也就是说,每个 HTTP 请求需要一个数据库连接。

我见过的例子在这里: https://github.com/PerfectlySoft/Perfect-MySQL 和这里: https://perfect.org/docs/MySQL.html

这样对吗?您必须使用 Perfect/mySQL?

为每个请求创建一个新的数据库连接

您仍然可以多次重用该连接,但请注意该连接不是线程安全的,因此必须在同一个连接上添加线程锁

import MySQL
import PerfectThread
#if os(Linux)
import Glibc
#else
import Darwin
#endif

let mysql = MySQL()
let lock = Threading.Lock()
var jobs = 10

func now(_ id: Int) {
  print("Job Now #", id)
  lock.doWithLock {
    let x = mysql.query(statement: "SELECT now() as time")
    guard x, let y = mysql.storeResults(),
    let row = y.next() else {
    print(mysql.errorMessage())
      return
    }
    print(row[0] ?? "Now() FAILED")
    y.close()
    jobs -= 1
  }
}

func user(_ id: Int) {
  print("Job Usr #", id)
  lock.doWithLock {
    let x = mysql.query(statement: "select User from user")
    guard x, let y = mysql.storeResults(),
      let row = y.next() else {
       print(mysql.errorMessage())
       return
   }
    print(row[0] ?? "User() FAILED")
    y.close()
    jobs -= 1
  }
}

_ = mysql.setOption(.MYSQL_SET_CHARSET_NAME, "utf8mb4")
guard mysql.connect(host: "127.0.0.1", user: "root", password: "your pass", db: "mysql") else {
  print(mysql.errorMessage())
  exit(0)
}

jobs = 10
for id in 0 ..< 5 {
  Threading.dispatch {
    now(id)
  }
  Threading.dispatch {
    user(id)
  }
}

while jobs > 0 {
  sleep(1)
}

mysql.close()

在此示例中,这两个函数共享同一个连接并且运行几次。没关系。但是,如果每个函数都运行在一个单独的线程中,那么就会导致失败。