mirror of
https://github.com/InsanusMokrassar/PlaguBot.git
synced 2024-11-21 15:13:46 +00:00
improve reconnect feature
This commit is contained in:
parent
dfbc7be6f2
commit
763718716d
@ -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
|
||||
)
|
@ -1,5 +1,8 @@
|
||||
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.Transient
|
||||
import org.jetbrains.exposed.sql.Database
|
||||
@ -18,29 +21,22 @@ data class DatabaseConfig(
|
||||
val driver: String = JDBC::class.qualifiedName!!,
|
||||
val username: String = "",
|
||||
val password: String = "",
|
||||
val waitForConnection: Boolean = true
|
||||
val reconnectOptions: DBConnectOptions? = DBConnectOptions()
|
||||
) {
|
||||
@Transient
|
||||
val database: Database by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
|
||||
while (true) {
|
||||
return@lazy try {
|
||||
Database.connect(
|
||||
url,
|
||||
driver,
|
||||
username,
|
||||
password
|
||||
).also {
|
||||
it.transactionManager.defaultIsolationLevel = Connection.TRANSACTION_SERIALIZABLE // Or Connection.TRANSACTION_READ_UNCOMMITTED
|
||||
}
|
||||
} catch (e: Throwable) {
|
||||
if (waitForConnection) {
|
||||
Thread.sleep(1000L)
|
||||
continue
|
||||
} else {
|
||||
throw e
|
||||
}
|
||||
val database: Database = (0 until (reconnectOptions ?.attempts ?: 1)).firstNotNullOfOrNull {
|
||||
runCatching {
|
||||
Database.connect(
|
||||
url,
|
||||
driver,
|
||||
username,
|
||||
password
|
||||
).also {
|
||||
it.transactionManager.defaultIsolationLevel = Connection.TRANSACTION_SERIALIZABLE // Or Connection.TRANSACTION_READ_UNCOMMITTED
|
||||
}
|
||||
}
|
||||
error("Unable to get database by some reason")
|
||||
}
|
||||
}.onFailure {
|
||||
logger.e(it)
|
||||
Thread.sleep(reconnectOptions ?.delay ?: return@onFailure)
|
||||
}.getOrNull()
|
||||
} ?: error("Unable to create database")
|
||||
}
|
||||
|
@ -4,7 +4,10 @@
|
||||
"driver": "org.sqlite.JDBC",
|
||||
"username": "OPTIONAL username",
|
||||
"password": "OPTIONAL password",
|
||||
"waitForConnection": true
|
||||
"reconnectOptions": {
|
||||
"attempts": 3,
|
||||
"delay": 1000
|
||||
}
|
||||
},
|
||||
"botToken": "1234567890:ABCDEFGHIJKLMNOP_qrstuvwxyz12345678",
|
||||
"plugins": [
|
||||
|
Loading…
Reference in New Issue
Block a user