協程

Kotlin 協程 是可掛起計算的例項,允許以命令式方式編寫非阻塞程式碼。在語言層面,suspend 函式為非同步操作提供了抽象,而在庫層面,kotlinx.coroutines 提供了諸如 async { } 這樣的函式和諸如 Flow 這樣的型別。

Spring Data 模組在以下範圍提供對協程的支援

  • DeferredFlow 返回值支援在 Kotlin 擴充套件中

依賴

kotlinx-coroutines-corekotlinx-coroutines-reactivekotlinx-coroutines-reactor 依賴項存在於 classpath 中時,協程支援被啟用

需要新增到 Maven pom.xml 中的依賴項
<dependency>
	<groupId>org.jetbrains.kotlinx</groupId>
	<artifactId>kotlinx-coroutines-core</artifactId>
</dependency>

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

<dependency>
	<groupId>org.jetbrains.kotlinx</groupId>
	<artifactId>kotlinx-coroutines-reactor</artifactId>
</dependency>
支援的版本為 1.3.0 及更高。

Reactive 如何轉換為協程?

對於返回值,從 Reactive 到 Coroutines API 的轉換如下

  • fun handler(): Mono<Void> 變為 suspend fun handler()

  • fun handler(): Mono<T> 變為 suspend fun handler(): Tsuspend fun handler(): T?,具體取決於 Mono 是否可能為空(優點是型別更加靜態化)

  • fun handler(): Flux<T> 變為 fun handler(): Flow<T>

Flow 是協程世界中 Flux 的等價物,適用於熱流或冷流、有限或無限流,主要區別如下

  • Flow 是推(push)模型,而 Flux 是推拉(push-pull)混合模型

  • 背壓透過掛起函式實現

  • Flow 只有一個單一的 掛起 collect 方法,並且運算子作為擴充套件實現

  • 藉助於協程,運算子很容易實現

  • 擴充套件允許向 Flow 新增自定義運算子

  • Collect 操作是掛起函式

  • map 運算子支援非同步操作(無需使用 flatMap),因為它接受一個掛起函式引數

閱讀這篇關於 使用 Spring、協程和 Kotlin Flow 實現響應式 的部落格文章,瞭解更多詳情,包括如何使用協程並行執行程式碼。

Repositories

以下是協程 Repository 的示例

interface CoroutineRepository : CoroutineCrudRepository<User, String> {

    suspend fun findOne(id: String): User

    fun findByFirstname(firstname: String): Flow<User>

    suspend fun findAllByFirstname(id: String): List<User>
}

協程 Repositories 構建在響應式 Repositories 的基礎上,透過 Kotlin 協程暴露資料訪問的非阻塞特性。協程 Repository 中的方法可以由查詢方法或自定義實現支援。呼叫自定義實現方法會將協程呼叫傳播到實際的實現方法(如果自定義方法是可 suspend 的),而無需實現方法返回諸如 MonoFlux 這樣的響應式型別。

請注意,根據方法宣告,協程上下文可能可用,也可能不可用。為了保留對上下文的訪問,請使用 suspend 宣告您的方法,或者返回一個支援上下文傳播的型別,例如 Flow

  • suspend fun findOne(id: String): User: 透過掛起一次性同步檢索資料。

  • fun findByFirstname(firstname: String): Flow<User>: 檢索資料流。Flow 被急切地建立,而資料在 Flow 互動(Flow.collect(…))時被獲取。

  • fun getUser(): User: 一次性檢索資料,但會阻塞執行緒且不傳播上下文。應避免使用此方法。

只有當 Repository 繼承 CoroutineCrudRepository 介面時,協程 Repositories 才會被發現。