我正在 Dart 中创建一个后端服务器应用程序,它使用 MySQL 数据库来存储数据。为了进行 SQL 调用,我使用 SqlJocky 中的 ConnectionPool。
应用程序启动时我会做什么:
- 创建一个存储 ConnectionPool 的单例
- 使用prepareExecute和query执行多个查询
在本地,这种方法运行良好。现在,我将开发版本推送到 Heroku,几分钟后就遇到连接问题。
所以我想知道,我是否需要从用于执行查询的池中关闭/释放单个连接?还是查询后的连接再次放入池中并免费使用?
所有 MySQL 存储的抽象基类:
abstract class MySQLStore {
MySQLStore(ConnectionPool connectionPool) {
this._connectionPool = connectionPool;
}
ConnectionPool get connectionPool => this._connectionPool;
ConnectionPool _connectionPool;
}
getAll方法的具体实现:
Future<List<T>> getAll() async {
Completer completer = new Completer();
connectionPool.query("SELECT id, name, description FROM role").then((result) {
return result.toList();
}).then((rows) {
completer.complete(this._processRows(rows));
}).catchError((error) {
// TODO: Better error handling.
print(error);
completer.complete(null);
});
return completer.future;
}
我得到的错误:
SocketException: OS Error: Connection timed out, errno = 110, address = ...
最佳答案
这并不能完全回答您的问题,但我认为您可以简化代码,例如:
Future<List<T>> getAll() async {
try {
var result = await connectionPool.query(
"SELECT id, name, description FROM role");
return this._processRows(await result.toList());
} catch(error) {
// TODO: Better error handling.
print(error);
return null;
}
}
我确信这里不需要关闭与查询
的连接。不过我不知道 prepareExecute
。
根据 SqlJocky 代码中的注释,数据库服务器可能需要相当长的时间才能释放连接。
也许您需要增加连接池大小(默认为 5),以便在 ConnectionPool
等待连接释放时不会耗尽连接。
关于mysql - SqlJocky 的 ConnectionPool 是否需要关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32045950/