Edd
06/17/2019, 2:26 PMHttpClient
which executes a long request. This call is triggered via a post
route, which looks something like this:
val http = HttpClient(Apache)
routing {
post("/api/start-job") {
<http://http.post|http.post><String>("<http://url-to-long-request>")
call.respond(HttpStatusCode.Accepted, "job started")
}
}
Sending a request to this route results in having to wait quite as the client makes a heavy request (it starts a job on another service). I'd like to simply send the request to <http://url-to-long-request>
and immediately return the 202
with "job started"
message. I could achieve this using an Executor
and wrapping the <http://http.post|http.post>
call, however I feel like that is not the right way to do this. Any suggestions on this?ribesg
06/17/2019, 2:36 PMlaunch { }
Edd
06/17/2019, 2:43 PMhttp
call still pauses the API):
coroutineScope {
launch(<http://Dispatchers.IO|Dispatchers.IO>) {
// http stuff
}
}
coroutineScope {
launch {
// http stuff
}
}
uli
06/17/2019, 10:15 PMGlobalScope
Edd
06/18/2019, 6:26 AMApplication code usually should use an application-defined CoroutineScope. Using async or launch on the instance of GlobalScope is highly discouraged.
From:
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/Edd
06/18/2019, 6:28 AMuli
06/18/2019, 2:33 PMEdd
06/19/2019, 6:06 AMGlobalScope
, just with a default dispatcher):
object IOCoroutineScope : CoroutineScope by CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO> + handler)
private val log = KotlinLogging.logger { }
private val handler = CoroutineExceptionHandler { _, exception ->
log.error("Unhandled error", exception)
}
Then, in my route handlers, I specify CoroutineScope
and pass in IOCoroutineScope
(so that I could pass a blocking scope in tests) and initialize them with IOCoroutineScope
. Then on this scope
, I do scope.launch
and stuff happens the way I want.
Also, <http://Dispatchers.IO|Dispatchers.IO>
is used in this case, as the async stuff makes HTTP requests (to Elastcisearch).
Thanks for the help!uli
06/19/2019, 9:48 AM