Ktor - post 协程未处理的错误
Ktor - post unhanldled error with coroutines
我是 Kotlin 和 Ktor 的新手,所以我尝试做简单的 post 请求。正如你在下面看到的,没有什么特别的。
routing {
post("/articles/add"){
val post = call.receive<ArticleRequest>()
println(post)
}
日志中显示的错误如下,我不明白为什么要在这里使用协程。
ERROR Application - Unhandled: POST - /articles/add
java.lang.IllegalStateException: Using blocking primitives on this dispatcher is not allowed. Consider using async channel instead or use blocking primitives in withContext(Dispatchers.IO) instead.
我使用的是1.4.2版本。如果有任何帮助,我将不胜感激。
如果您使用的是 Jackson,这是 bug 并且有一个建议的解决方法:
routing {
post("/articles/add") {
with(Dispatchers.IO) {
val post = call.receive<ArticleRequest>()
println(post)
}
}
}
或者你可以回滚到 1.4.1 直到 bug 被解决。
我在升级到 ktor 1.4.2 和 Kotlin 1.4.20 后遇到了同样的问题,我在这个特定项目上同时使用了 Moshi 和 Gson,但我不认为它们是造成这个问题的原因。
如果您有 'gradle.properties' 文件,请添加这些(或您希望使用的任何版本):
ktor_version=1.3.2
kotlin_version=1.3.70.
否则,在您的 'build.gradle' 文件中,为不同版本创建变量:
buildscript {
ext.kotlin_version = '1.3.70'
ext.ktor_version = '1.3.2'
repositories {
jcenter()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
然后同步您的 gradle、运行 项目..应该一切正常。
但是,如果您仍然遇到一些与 gradle 相关的问题,请尝试以下操作:
转到 gradle(文件夹)-> 包装器 -> 打开 gradle_wrapper.properties 并确保 url 的版本为 6.x.x 或 5.x.x。
我的目前看起来像这样:
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
我是 Kotlin 和 Ktor 的新手,所以我尝试做简单的 post 请求。正如你在下面看到的,没有什么特别的。
routing {
post("/articles/add"){
val post = call.receive<ArticleRequest>()
println(post)
}
日志中显示的错误如下,我不明白为什么要在这里使用协程。
ERROR Application - Unhandled: POST - /articles/add
java.lang.IllegalStateException: Using blocking primitives on this dispatcher is not allowed. Consider using async channel instead or use blocking primitives in withContext(Dispatchers.IO) instead.
我使用的是1.4.2版本。如果有任何帮助,我将不胜感激。
如果您使用的是 Jackson,这是 bug 并且有一个建议的解决方法:
routing {
post("/articles/add") {
with(Dispatchers.IO) {
val post = call.receive<ArticleRequest>()
println(post)
}
}
}
或者你可以回滚到 1.4.1 直到 bug 被解决。
我在升级到 ktor 1.4.2 和 Kotlin 1.4.20 后遇到了同样的问题,我在这个特定项目上同时使用了 Moshi 和 Gson,但我不认为它们是造成这个问题的原因。
如果您有 'gradle.properties' 文件,请添加这些(或您希望使用的任何版本):
ktor_version=1.3.2
kotlin_version=1.3.70.
否则,在您的 'build.gradle' 文件中,为不同版本创建变量:
buildscript {
ext.kotlin_version = '1.3.70'
ext.ktor_version = '1.3.2'
repositories {
jcenter()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
然后同步您的 gradle、运行 项目..应该一切正常。 但是,如果您仍然遇到一些与 gradle 相关的问题,请尝试以下操作:
转到 gradle(文件夹)-> 包装器 -> 打开 gradle_wrapper.properties 并确保 url 的版本为 6.x.x 或 5.x.x。
我的目前看起来像这样:
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists