78 lines
2.3 KiB
Kotlin
78 lines
2.3 KiB
Kotlin
import io.ktor.http.HttpStatusCode
|
|
import io.ktor.server.application.install
|
|
import io.ktor.server.cio.CIO
|
|
import io.ktor.server.engine.embeddedServer
|
|
import io.ktor.server.request.receiveText
|
|
import io.ktor.server.response.respond
|
|
import io.ktor.server.response.respondText
|
|
import io.ktor.server.routing.Route
|
|
import io.ktor.server.routing.get
|
|
import io.ktor.server.routing.post
|
|
import io.ktor.server.routing.route
|
|
import io.ktor.server.routing.routing
|
|
import io.ktor.server.websocket.WebSockets
|
|
import kotlinx.coroutines.Dispatchers
|
|
import kotlinx.coroutines.coroutineScope
|
|
import kotlinx.coroutines.currentCoroutineContext
|
|
import kotlinx.coroutines.newFixedThreadPoolContext
|
|
import kotlinx.coroutines.sync.Semaphore
|
|
import kotlinx.coroutines.sync.withPermit
|
|
import kotlinx.coroutines.withContext
|
|
import kotlin.coroutines.CoroutineContext
|
|
|
|
fun Route.subroute(){
|
|
var content = ""
|
|
|
|
get("get") {
|
|
call.respondText("Content: ${content}")
|
|
}
|
|
|
|
post("set"){
|
|
content = call.receiveText()
|
|
call.respond(HttpStatusCode.OK)
|
|
}
|
|
}
|
|
|
|
suspend fun executeQuery(queryName: String, ioContext: CoroutineContext = Dispatchers.IO): String{
|
|
withContext(ioContext){
|
|
//some blocking logic
|
|
}
|
|
return queryName
|
|
}
|
|
|
|
|
|
fun main() {
|
|
embeddedServer(CIO, port = 8080, host = "localhost") {
|
|
install(WebSockets)
|
|
|
|
val ioContext = newFixedThreadPoolContext(12, "DB") //Dispatchers.IO
|
|
|
|
routing {
|
|
get("/") {
|
|
val callerName = call.queryParameters["name"] ?: "World"
|
|
call.respondText("Hello $callerName!")
|
|
}
|
|
get("/query/{queryName}"){
|
|
val queryName = call.parameters["queryName"] ?: "query"
|
|
val queryResult = executeQuery(queryName, ioContext)
|
|
call.respondText("$queryName successful: $queryResult")
|
|
}
|
|
route("subroute"){
|
|
subroute()
|
|
}
|
|
route("subroute1"){
|
|
subroute()
|
|
}
|
|
|
|
route("producer"){
|
|
streamingModule()
|
|
}
|
|
|
|
get("aggregated"){
|
|
val result = aggregateFromService("ws://localhost:8080/producer")
|
|
call.respondText(result.toString())
|
|
}
|
|
|
|
}
|
|
}.start(wait = true)
|
|
} |