我想创建函数。第一个连接到DB,第二个是完全重新连接,如果第一个失败。使用mysql本地驱动程序连接到数据库后出现异常
在我的实验中,我在开始时关闭DB,以获得connect
块失败并调用重新连接块。之后,我打开数据库,并期待该连接块会成功,但我得到例外。
这里是我的代码:
bool connect()
{
if(connection is null)
{
scope(failure) reconnect(); // call reconnect if fail
this.connection = mydb.lockConnection();
writeln("connection done");
return true;
}
else
return false;
}
void reconnect()
{
writeln("reconnection block");
if(connection is null)
{
while(!connect) // continue till connection will not be established
{
Thread.sleep(3.seconds);
connectionsAttempts++;
logError("Connection to DB is not active...");
logError("Reconnection to DB attempt: %s", connectionsAttempts);
connect();
}
if(connection !is null)
{
logWarn("Reconnection to DB server done");
}
}
}
日志(几秒钟后接通DB):
reconnection block
reconnection block
connection done
Reconnection to DB server done
[email protected]:\Users\Dima\AppData\Roaming\dub\packages\vibe-d-0.7.30\vibe-d\source\vibe\core\drivers\libevent2.d(326): Failed to connect to host 194.87.235.42:3306: Connection timed out [WSAETIMEDOUT ]
我不明白为什么我后主动例外:Reconnection to DB server done
'lockConnection' - 是否应该有一个匹配的“解锁”? –