協程

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

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

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

依賴

當類路徑中包含 kotlinx-coroutines-corekotlinx-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 及更高版本。

響應式(Reactive)如何轉換為協程(Coroutines)?

對於返回值,從響應式 API 到協程 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,適用於熱流或冷流、有限流或無限流,主要區別如下

閱讀這篇關於使用 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: 透過 suspend 一次性同步檢索資料。

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

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

只有當 Repository 擴充套件 CoroutineCrudRepository 介面時,才能發現協程 Repository。