Browse Source

database connection

mdportnov-mac 5 months ago
parent
commit
c1da5a9a7b

+ 6 - 4
build.gradle.kts

@@ -36,11 +36,13 @@ dependencies {
     implementation("io.ktor:ktor-auth-jwt:$ktor_version")
     implementation("io.ktor:ktor-server-sessions:$ktor_version")
     implementation("io.ktor:ktor-server-host-common:$ktor_version")
-    implementation("io.ktor:ktor-metrics:$ktor_version")
-    implementation("io.ktor:ktor-metrics-micrometer:$ktor_version")
-    implementation("io.micrometer:micrometer-registry-prometheus:$prometeus_version")
+
+    implementation("org.postgresql:postgresql:42.3.3")
+    implementation("com.zaxxer:HikariCP:5.0.1")
+    implementation("org.jetbrains.exposed:exposed:0.17.14")
+    implementation("io.ktor:ktor-server-tomcat:$ktor_version")
+
     implementation("io.ktor:ktor-serialization:$ktor_version")
-    implementation("io.ktor:ktor-server-netty:$ktor_version")
     implementation("ch.qos.logback:logback-classic:$logback_version")
     testImplementation("io.ktor:ktor-server-tests:$ktor_version")
     testImplementation("org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version")

+ 5 - 4
src/main/kotlin/ru/mephi/Application.kt

@@ -1,16 +1,17 @@
 package ru.mephi
 
 import io.ktor.server.engine.*
-import io.ktor.server.netty.*
+import io.ktor.server.tomcat.*
+import ru.mephi.database.DatabaseFactory
 import ru.mephi.plugins.*
 
 fun main() {
-    embeddedServer(Netty, port = 8080, host = "0.0.0.0") {
+    DatabaseFactory.init()
+    embeddedServer(Tomcat, port = 8080, host = "127.0.0.1" ) {
         configureRouting()
         configureSecurity()
         configureHTTP()
-        configureMonitoring()
         configureSerialization()
         configureAdministration()
-    }.start(wait = true)
+    }.start()
 }

+ 54 - 0
src/main/kotlin/ru/mephi/database/DatabaseFactory.kt

@@ -0,0 +1,54 @@
+package ru.mephi.database
+
+import com.typesafe.config.ConfigFactory
+import com.zaxxer.hikari.HikariConfig
+import com.zaxxer.hikari.HikariDataSource
+import io.ktor.config.*
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.launch
+import org.jetbrains.exposed.sql.Database
+import org.jetbrains.exposed.sql.transactions.transaction
+
+
+object DatabaseFactory {
+    private val appConfig = HoconApplicationConfig(ConfigFactory.load())
+    private val dbUrl = appConfig.property("db.jdbcUrl").getString()
+    private val dbUser = appConfig.property("db.dbUser").getString()
+    private val dbPassword = appConfig.property("db.dbPassword").getString()
+
+    fun init() {
+        Database.connect(hikari())
+
+        dbQuery {
+            val rs = connection.createStatement().executeQuery(
+                """ 
+                    SELECT table_name
+                    FROM information_schema.tables
+                    WHERE table_schema = 'public'
+                    ORDER BY table_name;
+                """.trimIndent()
+            )
+            while (rs.next()) {
+                val tableName = rs.getString(1)
+                println(tableName)
+            }
+        }
+    }
+
+    private fun hikari(): HikariDataSource {
+        val config = HikariConfig()
+        config.driverClassName = "org.postgresql.Driver"
+        config.jdbcUrl = dbUrl
+        config.username = dbUser
+        config.password = dbPassword
+        config.maximumPoolSize = 3
+        config.idleTimeout = 10000
+//        config.maxLifetime
+//        config.isAutoCommit = false
+        config.connectionTimeout = 300
+//        config.transactionIsolation = "TRANSACTION_REPEATABLE_READ"
+        config.validate()
+        return HikariDataSource(config)
+    }
+}

+ 10 - 0
src/main/kotlin/ru/mephi/database/dbQuery.kt

@@ -0,0 +1,10 @@
+package ru.mephi.database
+
+import kotlinx.coroutines.*
+import org.jetbrains.exposed.sql.Transaction
+import org.jetbrains.exposed.sql.transactions.transaction
+
+fun <T> dbQuery(statement: Transaction.() -> T): Job =
+    CoroutineScope(Dispatchers.IO).launch {
+        transaction { statement() }
+    }

+ 14 - 14
src/main/kotlin/ru/mephi/plugins/HTTP.kt

@@ -8,18 +8,18 @@ import io.ktor.response.*
 import io.ktor.request.*
 
 fun Application.configureHTTP() {
-    install(CachingHeaders) {
-        options { outgoingContent ->
-            when (outgoingContent.contentType?.withoutParameters()) {
-                ContentType.Text.CSS -> CachingOptions(CacheControl.MaxAge(maxAgeSeconds = 24 * 60 * 60))
-                else -> null
-            }
-        }
-    }
-    install(HttpsRedirect) {
-        // The port to redirect to. By default 443, the default HTTPS port.
-        sslPort = 443
-        // 301 Moved Permanently, or 302 Found redirect.
-        permanentRedirect = true
-    }
+//    install(CachingHeaders) {
+//        options { outgoingContent ->
+//            when (outgoingContent.contentType?.withoutParameters()) {
+//                ContentType.Text.CSS -> CachingOptions(CacheControl.MaxAge(maxAgeSeconds = 24 * 60 * 60))
+//                else -> null
+//            }
+//        }
+//    }
+//    install(HttpsRedirect) {
+//        // The port to redirect to. By default 443, the default HTTPS port.
+//        sslPort = 443
+//        // 301 Moved Permanently, or 302 Found redirect.
+//        permanentRedirect = true
+//    }
 }

+ 0 - 23
src/main/kotlin/ru/mephi/plugins/Monitoring.kt

@@ -1,23 +0,0 @@
-package ru.mephi.plugins
-
-import io.ktor.features.*
-import org.slf4j.event.*
-import io.ktor.request.*
-import io.micrometer.prometheus.*
-import io.ktor.metrics.micrometer.*
-import io.ktor.application.*
-import io.ktor.response.*
-
-fun Application.configureMonitoring() {
-    install(CallLogging) {
-        level = Level.INFO
-        filter { call -> call.request.path().startsWith("/") }
-    }
-
-    val appMicrometerRegistry = PrometheusMeterRegistry(PrometheusConfig.DEFAULT)
-
-    install(MicrometerMetrics) {
-        registry = appMicrometerRegistry
-        // ...
-    }
-}

+ 2 - 2
src/main/kotlin/ru/mephi/plugins/Routing.kt

@@ -7,10 +7,10 @@ import io.ktor.features.*
 import io.ktor.application.*
 import io.ktor.response.*
 import io.ktor.request.*
+import ru.mephi.routes.info.infoRoute
 
 fun Application.configureRouting() {
-
-
     routing {
+        infoRoute()
     }
 }

+ 8 - 8
src/main/kotlin/ru/mephi/plugins/Security.kt

@@ -13,7 +13,7 @@ import io.ktor.request.*
 
 fun Application.configureSecurity() {
 
-    authentication {
+//    authentication {
 //        jwt {
 //            val jwtAudience = environment.config.property("jwt.audience").getString()
 //            realm = environment.config.property("jwt.realm").getString()
@@ -28,11 +28,11 @@ fun Application.configureSecurity() {
 //                if (credential.payload.audience.contains(jwtAudience)) JWTPrincipal(credential.payload) else null
 //            }
 //        }
-    }
-    data class MySession(val count: Int = 0)
-    install(Sessions) {
-        cookie<MySession>("MY_SESSION") {
-            cookie.extensions["SameSite"] = "lax"
-        }
-    }
+//    }
+//    data class MySession(val count: Int = 0)
+//    install(Sessions) {
+//        cookie<MySession>("MY_SESSION") {
+//            cookie.extensions["SameSite"] = "lax"
+//        }
+//    }
 }

+ 0 - 2
src/main/kotlin/ru/mephi/plugins/Serialization.kt

@@ -3,8 +3,6 @@ package ru.mephi.plugins
 import io.ktor.serialization.*
 import io.ktor.features.*
 import io.ktor.application.*
-import io.ktor.response.*
-import io.ktor.request.*
 
 fun Application.configureSerialization() {
     install(ContentNegotiation) {

+ 15 - 0
src/main/kotlin/ru/mephi/routes/info/infoController.kt

@@ -0,0 +1,15 @@
+package ru.mephi.routes.info
+
+import io.ktor.application.*
+import io.ktor.response.*
+import io.ktor.routing.*
+
+fun Application.infoRoute() {
+    routing {
+        route("info") {
+            get {
+                call.respond("Server is running")
+            }
+        }
+    }
+}

+ 5 - 0
src/main/resources/application.conf

@@ -0,0 +1,5 @@
+db {
+    jdbcUrl = "jdbc:postgresql://localhost:5432/postgres"
+    dbUser = postgres
+    dbPassword = realpongo
+}

+ 0 - 18
src/test/kotlin/ru/mephi/ApplicationTest.kt

@@ -1,24 +1,6 @@
 package ru.mephi
 
-import io.ktor.routing.*
 import io.ktor.http.*
-import io.ktor.auth.*
-import io.ktor.util.*
-import io.ktor.auth.jwt.*
-import com.auth0.jwt.JWT
-import com.auth0.jwt.JWTVerifier
-import com.auth0.jwt.algorithms.Algorithm
-import io.ktor.sessions.*
-import io.ktor.http.content.*
-import io.ktor.features.*
-import org.slf4j.event.*
-import io.ktor.request.*
-import io.micrometer.prometheus.*
-import io.ktor.metrics.micrometer.*
-import io.ktor.serialization.*
-import io.ktor.server.engine.*
-import io.ktor.application.*
-import io.ktor.response.*
 import kotlin.test.*
 import io.ktor.server.testing.*
 import ru.mephi.plugins.*