協程

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

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

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

依賴

kotlinx-coroutines-core, kotlinx-coroutines-reactivekotlinx-coroutines-reactor 依賴項在類路徑中時,將啟用協程支援

要新增到 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 及以上。

響應式如何轉換為協程?

對於返回值,從響應式到協程 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-based),而 Flux 是推拉混合(push-pull hybrid)

  • 背壓(Backpressure)透過掛起函式實現

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

  • 由於協程,運算子易於實現

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

  • collect 操作是掛起函式

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

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

Repository

這是一個協程 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>
}

協程 Repository 構建在響應式 Repository 之上,透過 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 介面時,才會發現協程 Repository。