我想創建函數。第一個連接到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' - 是否應該有一個匹配的「解鎖」? –