協程
相依性
當類別路徑中存在 kotlinx-coroutines-core
、kotlinx-coroutines-reactive
和 kotlinx-coroutines-reactor
相依性時,會啟用協程支援
<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 到協程 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>
Flow
是協程世界中 Flux
的等效物,適用於熱或冷串流、有限或無限串流,具有以下主要差異
-
Flow
是推送式,而Flux
是推送-拉取混合式 -
背壓透過暫停函數實作
-
Flow
只有一個 單一暫停collect
方法,而運算子實作為擴充功能 -
擴充功能允許將自訂運算子新增至
Flow
-
Collect 運算為暫停函數
-
map
運算子 支援非同步操作(不需要flatMap
),因為它採用暫停函數參數
閱讀這篇關於 使用 Spring、協程和 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 上的方法可以由查詢方法或自訂實作來支援。如果自訂方法是可 suspend
的,則調用自訂實作方法會將協程調用傳播到實際的實作方法,而無需實作方法傳回諸如 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 介面時,才會發現協程 repository。 |