協程
依賴
當 classpath 中包含 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 的轉換如下
-
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
新增自定義運算子 -
收集操作是可暫停函式
-
map
運算子 支援非同步操作(無需flatMap
),因為它接受一個可暫停函式引數
閱讀這篇關於 使用 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
函式,則會將協程呼叫傳播到實際實現方法,而無需實現方法返回 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。 |