使用Objectify捕获IllegalStateException

问题描述 投票:1回答:1

我使用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>
    ...

Boostrapper

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$2$2.invokeSuspend(Application.kt:50) ~[classes/:?]
    at com.group.ApplicationKt$module$2$2.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模拟器数据存储区启动”来运行数据存储区。它肯定运行。可能是无法连接到它吗?

当我运行应用程序时使用appengineRun,是否还运行数据存储库?

google-app-engine kotlin google-cloud-platform objectify ktor
1个回答
0
投票

问题是ktor使用协程。协程默认在线程池中运行,并且ObjectifyFilter仅对于接收请求的线程是活动的。我使用此解决方法,直到找到更好的东西:

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

Unconfined调度程序在启动协程的同一线程中运行协程,至少直到第一次挂起为止。

© www.soinside.com 2019 - 2024. All rights reserved.