協程

Kotlin 協程是可以暫停的運算實例,允許以命令式的方式編寫非阻塞程式碼。在語言方面,suspend 函數為非同步操作提供了抽象化,而在函式庫方面,kotlinx.coroutines 提供了諸如 async { } 之類的函數和諸如 Flow 之類的類型。

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

  • 在 Kotlin 擴充功能中支援 DeferredFlow 回傳值

相依性

當 classpath 中存在 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 及以上。

反應式如何轉換為協程?

對於回傳值,從反應式到協程 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 的等效項,適用於熱或冷流、有限或無限流,具有以下主要差異

請閱讀這篇關於 Going Reactive with Spring, Coroutines and 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>
}

協程 repository 建構於反應式 repository 之上,以透過 Kotlin 的協程公開資料存取的非阻塞特性。協程 repository 上的方法可以由查詢方法或自訂實作來支援。如果自訂方法是可暫停的,則調用自訂實作方法會將協程調用傳播到實際的實作方法,而無需實作方法傳回反應式類型,例如 MonoFlux

請注意,根據方法宣告,協程 context 可能可用也可能不可用。若要保留對 context 的存取權,請使用 suspend 宣告您的方法,或傳回啟用 context 傳播的類型,例如 Flow

  • suspend fun findOne(id: String): User:透過暫停同步擷取資料一次。

  • fun findByFirstname(firstname: String): Flow<User>:擷取資料流。Flow 是預先建立的,而資料是在 Flow 互動 (Flow.collect(…) ) 時擷取的。

  • fun getUser(): User:擷取資料一次,**阻塞執行緒**且不進行 context 傳播。應避免使用此方法。

僅當 repository 擴充 CoroutineCrudRepository 介面時,才會發現協程 repository。