【问题标题】:How to use kotlin coroutines with reactive spring data如何将 kotlin 协程与反应式弹簧数据一起使用
【发布时间】:2020-07-05 17:44:53
【问题描述】:

我正在尝试将一些项目从 Spring Reactor 迁移到 kotlin 协程。我有一些基于 spring webflux 的控制器:

@RestController
class Controller(val productRepository: ProductsRepository) {

    @GetMapping("/product")
    fun find(@RequestParam id: String): Mono<Product> {
        return productRepository.findById(id)
    }
}

此控制器使用响应式弹簧数据存储库:

@Repository
interface ProductsRepository : ReactiveMongoRepository<Product, String>

根据这个官方文档 - https://docs.spring.io/spring/docs/5.2.0.M1/spring-framework-reference/languages.html#how-reactive-translates-to-coroutines,我在控制器中的函数 find 应该被翻译成 suspend fun 并且这个函数应该返回 Product 类的实例而不是 Product 的响应式 Mono 包装器。类似的东西:

@RestController
class Controller(val productRepository: ProductsRepository) {

    @GetMapping("/product")
    suspend fun find(@RequestParam id: String): Product {
        return productRepository.findById(id)
    }
}

但我的 productRepository 处理 Mono 和 Flux,而不是挂起的函数。在这种情况下,我应该如何正确使用 spring 数据抽象?

【问题讨论】:

    标签: spring kotlin spring-data kotlin-coroutines


    【解决方案1】:

    这可以通过有用的 kotlinx-coroutines-reactor 帮助程序库来实现,它为项目反应器 Publisher 提供有用的扩展方法,以帮助将 MonoFlux 转换为 kotlin 协程。

    先添加一个依赖

     <dependency>
         <groupId>org.jetbrains.kotlinx</groupId>
         <artifactId>kotlinx-coroutines-reactor</artifactId>
     </dependency>
    

    (如果您使用 spring-boot,则不必指定版本,因为它会为您管理它)

    您现在可以使用kotlinx.coroutines.reactive.awaitFirstOrNullMono&lt;Product&gt; 转换为Product? 并“等待”结果。

    @RestController
    class Controller(val productRepository: ProductsRepository) {
    
        @GetMapping("/product")
        suspend fun find(@RequestParam id: String): Product? {
            return productRepository.findById(id).awaitFirstOrNull()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-02
      • 2020-10-02
      • 2017-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-25
      • 1970-01-01
      相关资源
      最近更新 更多