協程
Kotlin 協程 (Coroutines) 是可掛起計算的例項,允許以命令式方式編寫非阻塞程式碼。在語言層面,suspend
函式為非同步操作提供了抽象,而在庫層面,kotlinx.coroutines 提供了諸如 async { }
等函式以及諸如 Flow
等型別。
Spring Data 模組在以下範圍內提供對 Coroutines 的支援
依賴項
當 classpath 中包含 kotlinx-coroutines-core
、kotlinx-coroutines-reactive
和 kotlinx-coroutines-reactor
依賴項時,將啟用 Coroutines 支援
<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 到 Coroutines API 的轉換如下
-
fun handler(): Mono<Void>
變為suspend fun handler()
-
fun handler(): Mono<T>
變為suspend fun handler(): T
或suspend fun handler(): T?
,具體取決於Mono
是否可能為空(這樣做的好處是型別更加靜態化) -
fun handler(): Flux<T>
變為fun handler(): Flow<T>
在 Coroutines 世界中,Flow
等同於 Flux
,適用於熱流或冷流,有限流或無限流,主要區別如下
-
Flow
是推(push)模式,而Flux
是推拉(push-pull)混合模式 -
背壓透過掛起函式實現
-
Flow
只有一個 掛起方法collect
,並且運算子實現為 擴充套件函式 -
藉助於 Coroutines,運算子易於實現
-
擴充套件函式允許向
Flow
新增自定義運算子 -
Collect 操作是掛起函式
-
map
運算子 支援非同步操作(無需flatMap
),因為它接受一個掛起函式引數
閱讀這篇關於 使用 Spring、Coroutines 和 Kotlin Flow 實現響應式程式設計 的部落格文章,瞭解更多詳細資訊,包括如何使用 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 repository 構建在響應式 repository 之上,透過 Kotlin 的 Coroutines 暴露出資料訪問的非阻塞特性。Coroutines repository 中的方法可以由查詢方法或自定義實現支援。如果自定義方法是可 suspend
的,那麼呼叫自定義實現方法會將 Coroutines 呼叫傳播到實際實現方法,而無需實現方法返回像 Mono
或 Flux
這樣的響應式型別。
請注意,根據方法宣告的不同,協程上下文可能可用,也可能不可用。要保留對上下文的訪問,請使用 suspend
宣告方法,或返回一個支援上下文傳播的型別,例如 Flow
。
-
suspend fun findOne(id: String): User
: 透過掛起一次性同步檢索資料。 -
fun findByFirstname(firstname: String): Flow<User>
: 檢索資料流。Flow
會被急切地建立,而資料則在與Flow
互動(Flow.collect(…)
)時才被獲取。 -
fun getUser(): User
: 一次性檢索資料,阻塞執行緒且不傳播上下文。應避免這樣做。
只有當 repository 擴充套件 CoroutineCrudRepository 介面時,才會發現 Coroutines repository。 |