improve reconnect feature

This commit is contained in:
InsanusMokrassar 2022-09-04 15:07:30 +06:00
parent dfbc7be6f2
commit 763718716d
3 changed files with 31 additions and 23 deletions

View File

@ -0,0 +1,9 @@
package dev.inmo.plagubot.config
import kotlinx.serialization.Serializable
@Serializable
data class DBConnectOptions(
val attempts: Int = 3,
val delay: Long = 1000L
)

View File

@ -1,5 +1,8 @@
package dev.inmo.plagubot.config package dev.inmo.plagubot.config
import dev.inmo.kslog.common.e
import dev.inmo.kslog.common.logger
import kotlinx.coroutines.delay
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient import kotlinx.serialization.Transient
import org.jetbrains.exposed.sql.Database import org.jetbrains.exposed.sql.Database
@ -18,12 +21,11 @@ data class DatabaseConfig(
val driver: String = JDBC::class.qualifiedName!!, val driver: String = JDBC::class.qualifiedName!!,
val username: String = "", val username: String = "",
val password: String = "", val password: String = "",
val waitForConnection: Boolean = true val reconnectOptions: DBConnectOptions? = DBConnectOptions()
) { ) {
@Transient @Transient
val database: Database by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { val database: Database = (0 until (reconnectOptions ?.attempts ?: 1)).firstNotNullOfOrNull {
while (true) { runCatching {
return@lazy try {
Database.connect( Database.connect(
url, url,
driver, driver,
@ -32,15 +34,9 @@ data class DatabaseConfig(
).also { ).also {
it.transactionManager.defaultIsolationLevel = Connection.TRANSACTION_SERIALIZABLE // Or Connection.TRANSACTION_READ_UNCOMMITTED it.transactionManager.defaultIsolationLevel = Connection.TRANSACTION_SERIALIZABLE // Or Connection.TRANSACTION_READ_UNCOMMITTED
} }
} catch (e: Throwable) { }.onFailure {
if (waitForConnection) { logger.e(it)
Thread.sleep(1000L) Thread.sleep(reconnectOptions ?.delay ?: return@onFailure)
continue }.getOrNull()
} else { } ?: error("Unable to create database")
throw e
}
}
}
error("Unable to get database by some reason")
}
} }

View File

@ -4,7 +4,10 @@
"driver": "org.sqlite.JDBC", "driver": "org.sqlite.JDBC",
"username": "OPTIONAL username", "username": "OPTIONAL username",
"password": "OPTIONAL password", "password": "OPTIONAL password",
"waitForConnection": true "reconnectOptions": {
"attempts": 3,
"delay": 1000
}
}, },
"botToken": "1234567890:ABCDEFGHIJKLMNOP_qrstuvwxyz12345678", "botToken": "1234567890:ABCDEFGHIJKLMNOP_qrstuvwxyz12345678",
"plugins": [ "plugins": [