使用 Objectify 捕获 IllegalStateException

Catch IllegalStateException with Objectify

我使用 Objectify 6.0.5,Ktor 1.2.6,com.google.appengine:appengine:1.9.60

我通过教程 https://github.com/objectify/objectify/wiki/Setup

设置了 web.xml,引导程序

web.xml

    ...
    <listener>
        <listener-class>com.group.Bootstrapper</listener-class>
    </listener>

    <filter>
        <filter-name>ObjectifyFilter</filter-name>
        <filter-class>com.googlecode.objectify.ObjectifyFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>ObjectifyFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    ...

助推器

class Bootstrapper : ServletContextListener {
    override fun contextInitialized(sce: ServletContextEvent?) {
        println("         contextInitialized")
        ObjectifyService.init(
            ObjectifyFactory()
        )

        ObjectifyService.register(User::class.java)
    }

    override fun contextDestroyed(sce: ServletContextEvent?) {}
}

当我调用这个方法时

    fun save(entity: T) {
        ofy().save().entity(entity)
    }

我发现错误

2020-01-05 17:55:09 ERROR Application:104 - Unhandled: GET - /test
java.lang.IllegalStateException: You must call ObjectifyService.init() before using Objectify
    at com.google.common.base.Preconditions.checkState(Preconditions.java:511) ~[guava-28.1-android.jar:?]
    at com.googlecode.objectify.ObjectifyService.factory(ObjectifyService.java:34) ~[objectify-6.0.5.jar:?]
    at com.googlecode.objectify.ObjectifyService.ofy(ObjectifyService.java:51) ~[objectify-6.0.5.jar:?]
    at com.group.dao.BaseDao.listAll(BaseDao.kt:15) ~[classes/:?]
    at com.group.ApplicationKt$module.invokeSuspend(Application.kt:50) ~[classes/:?]
    at com.group.ApplicationKt$module.invoke(Application.kt) ~[classes/:?]
    at io.ktor.util.pipeline.SuspendFunctionGun.loop(PipelineContext.kt:268) ~[ktor-utils-jvm-1.2.6.jar:1.2.6]
    at io.ktor.util.pipeline.SuspendFunctionGun.proceed(PipelineContext.kt:141) ~[ktor-utils-jvm-1.2.6.jar:1.2.6]
    at io.ktor.util.pipeline.SuspendFunctionGun.execute(PipelineContext.kt:161) ~[ktor-utils-jvm-1.2.6.jar:1.2.6]
    at io.ktor.util.pipeline.Pipeline.execute(Pipeline.kt:27) ~[ktor-utils-jvm-1.2.6.jar:1.2.6]
    at io.ktor.routing.Routing.executeResult(Routing.kt:147) ~[ktor-server-core-1.2.6.jar:1.2.6]
...

我 运行 数据存储使用 'gcloud beta emulators datastore start'。绝对是运行。可能是没有连接到它?

当我运行应用程序使用appengineRun时,datastore也是运行?

问题是 ktor 使用协程。默认情况下,协程 运行 在线程池中, ObjectifyFilter 仅对接收请求的线程有效。我使用此解决方法,直到找到更好的方法:

get(path) {
    withContext(Dispatchers.Unconfined) {
        val content = page.doGet()
        call.respond(content)
    }
}

Unconfined 调度程序 运行 在启动它的同一线程中提供协程,至少在第一次挂起之前。