首页 > 解决方案 > Webflux Kotlin Coroutines Flow 不返回任何结果

问题描述

我的 Spring 存储库实现了一个函数来返回用户的 kotlinx.coroutines.flow.Flow,但即使我的数据库中有一些记录,这个流似乎总是空的。

我正在使用带有 Kotlin 协程支持的 Spring Boot 2.2.0-SNAPSHOT。我在存储库中创建了两种方法,一种用于创建用户,另一种用于列出所有用户。创建用户的工作,我可以在我的数据库中看到这个用户。列出现有用户的第二个总是返回一个空列表,即使我的数据库有一些记录。

我在 Spring 应用程序旁边使用 PostGres 10.1 docker 实例。

完整的项目可在 github 上找到:https ://github.com/kizux/demo-spring-webflux-kotlin

这是我的存储库的方法实现:

src/main/kotlin/fr/kizux/kotlindemocoroutines/repository/UserRepository.kt

fun findAll(): Flow<User> = dbClient.select().from(TABLE_USER_NAME).asType<User>().fetch().flow()

这是由这个处理程序返回的:src/main/kotlin/fr/kizux/kotlindemocoroutines/handler/UserHandler.kt

suspend fun getAll(req: ServerRequest): ServerResponse = ServerResponse.ok().bodyAndAwait(userRepo.findAll())

并路由在:src/main/kotlin/fr/kizux/kotlindemocoroutines/configuration/RouterConfig.kt

@Bean
    fun userRoutes(userHandler: UserHandler) = coRouter {
        "/user".nest {
            GET("", userHandler::getAll)
            POST("", userHandler::create)
        }
    }

我还尝试在我的应用程序启动时添加一个日志:src/main/kotlin/fr/kizux/kotlindemocoroutines/KotlinDemoCoroutinesApplication.kt

@EventListener(value = [ApplicationReadyEvent::class])
    fun init() {
        runBlocking {
            userRepo.save(User(email="j@hn.doe", signInDate=LocalDateTime.now()))
            userRepo.findAll().onEach { user -> println("Here is $user") }
        }
    }

目前我得到的唯一回报是一个空的 json 对象:

http://localhost:8080/user - HTTP 200 = {}

我想我应该获得更多类似的东西:

http://localhost:8080/user - HTTP 200 = {"id": 1, "email": "j@hn.doe", "signInDate": "whatever"}

标签: spring-webfluxkotlin-coroutines

解决方案


我改变了我的依赖

implementation("org.springframework.data:spring-data-r2dbc:BUILD-SNAPSHOT")

implementation("org.springframework.data:spring-data-r2dbc:1.0.0.M2")

它现在有效


推荐阅读