Skip to content

Commit

Permalink
Ktor optimize and update (#9444)
Browse files Browse the repository at this point in the history
* fixed batch writes

* upgraded Ktor to latest

---------

Co-authored-by: Ilya Nemtsev <[email protected]>
  • Loading branch information
inemtsev and Ilya Nemtsev authored Dec 9, 2024
1 parent cda709d commit 884a516
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
2 changes: 1 addition & 1 deletion frameworks/Kotlin/ktor/ktor/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

<properties>
<kotlin.version>2.0.21</kotlin.version>
<ktor.version>3.0.1</ktor.version>
<ktor.version>3.0.2</ktor.version>
<serialization.version>1.7.3</serialization.version>
<kotlinx.html.version>0.11.0</kotlinx.html.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import org.jetbrains.ktor.benchmarks.Constants.UPDATE_QUERY
import org.jetbrains.ktor.benchmarks.Constants.WORLD_QUERY
import java.sql.Connection
import java.util.concurrent.ThreadLocalRandom
import kotlin.random.Random

@Serializable
data class Message(val message: String)
Expand Down Expand Up @@ -49,7 +50,7 @@ fun Application.main() {
}

get("/db") {
val random = ThreadLocalRandom.current()
val random = Random.Default

val world = withContext(databaseDispatcher) {
pool.connection.use { connection ->
Expand All @@ -67,7 +68,7 @@ fun Application.main() {
call.respondText(Json.encodeToString(world), ContentType.Application.Json)
}

fun Connection.selectWorlds(queries: Int, random: ThreadLocalRandom): List<World> {
fun Connection.selectWorlds(queries: Int, random: Random): List<World> {
val result = ArrayList<World>(queries)
prepareStatement(WORLD_QUERY).use { statement ->
repeat(queries) {
Expand All @@ -85,7 +86,7 @@ fun Application.main() {

get("/queries") {
val queries = call.queries()
val random = ThreadLocalRandom.current()
val random = Random.Default

val result = withContext(databaseDispatcher) {
pool.connection.use { it.selectWorlds(queries, random) }
Expand Down Expand Up @@ -130,7 +131,7 @@ fun Application.main() {

get("/updates") {
val queries = call.queries()
val random = ThreadLocalRandom.current()
val random = Random.Default
val result: List<World>

withContext(databaseDispatcher) {
Expand All @@ -139,14 +140,14 @@ fun Application.main() {

result.forEach { it.randomNumber = random.nextInt(dbRows) + 1 }

connection.prepareStatement(UPDATE_QUERY)
.use { updateStatement ->
connection.prepareStatement(UPDATE_QUERY).use { updateStatement ->
for ((id, randomNumber) in result) {
updateStatement.setInt(1, randomNumber)
updateStatement.setInt(2, id)

updateStatement.executeUpdate()
updateStatement.addBatch()
}

updateStatement.executeBatch()
}
}
}
Expand Down

0 comments on commit 884a516

Please sign in to comment.