Created
September 16, 2022 02:56
-
-
Save anuragsoni/3680b9c30ba07ff16896490310c4fa7a to your computer and use it in GitHub Desktop.
Vert.x Web + Kotlin Coroutines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile | |
plugins { | |
kotlin("jvm") version "1.7.10" | |
} | |
group = "org.example" | |
version = "1.0-SNAPSHOT" | |
repositories { | |
mavenCentral() | |
} | |
dependencies { | |
implementation("io.vertx:vertx-web:4.3.3") | |
implementation("io.vertx:vertx-lang-kotlin-coroutines:4.3.3") | |
implementation("io.vertx:vertx-lang-kotlin:4.3.3") | |
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4") | |
} | |
tasks.withType<KotlinCompile> { | |
kotlinOptions.jvmTarget = "1.8" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io.vertx.core.Vertx | |
import io.vertx.ext.web.Route | |
import io.vertx.ext.web.Router | |
import io.vertx.ext.web.RoutingContext | |
import io.vertx.kotlin.coroutines.CoroutineVerticle | |
import io.vertx.kotlin.coroutines.await | |
import kotlin.coroutines.CoroutineContext | |
import kotlinx.coroutines.CoroutineScope | |
import kotlinx.coroutines.delay | |
import kotlinx.coroutines.launch | |
suspend fun coroutineDemo(): String { | |
delay(3000) | |
return "Hello World" | |
} | |
public fun Route.coroutineHandler( | |
coroutineContext: CoroutineContext, | |
userHandler: suspend (RoutingContext) -> Unit | |
) = handler { routingContext -> | |
CoroutineScope(coroutineContext).launch { | |
try { | |
userHandler(routingContext) | |
} catch (exception: Exception) { | |
routingContext.fail(exception) | |
} | |
} | |
} | |
class MainVerticle() : CoroutineVerticle() { | |
override suspend fun start() { | |
val router = Router.router(vertx); | |
router.route("/hello").coroutineHandler(coroutineContext) { routingContext -> | |
val payload = coroutineDemo() | |
routingContext.response().send(payload) | |
} | |
vertx.createHttpServer().requestHandler(router).listen(8080).await() | |
} | |
} | |
fun main() { | |
val vertx = Vertx.vertx() | |
vertx.deployVerticle(MainVerticle()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment