協程 (Coroutines)

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

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

相依性 (Dependencies)

當類路徑中存在 kotlinx-coroutines-corekotlinx-coroutines-reactivekotlinx-coroutines-reactor 相依性時,協程 (Coroutines) 支援會被啟用

在 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)?

對於回傳值,從反應式 (Reactive) API 到協程 (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 是協程 (Coroutines) 世界中 Flux 的等效物,適用於熱或冷串流、有限或無限串流,具有以下主要差異

閱讀這篇關於 使用 Spring、協程 (Coroutines) 和 Kotlin Flow 實現反應式 (Reactive) 的部落格文章,以了解更多詳細資訊,包括如何使用協程 (Coroutines) 並行執行程式碼。

Repositories

以下是協程 (Coroutines) 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>
}

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

請注意,根據方法宣告,協程 (coroutine) 上下文可能可用也可能不可用。為了保留對上下文的存取權限,請使用 suspend 宣告您的方法,或回傳啟用上下文傳播的類型,例如 Flow

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

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

  • fun getUser(): User:取得資料一次,阻塞執行緒 (blocking the thread) 且沒有上下文傳播。 應避免這樣做。

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