協程
依賴項
當 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 及以上。 |
Reactive 如何轉換為協程?
對於返回值,從響應式到協程 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 走向響應式 的部落格文章,瞭解更多細節,包括如何使用協程併發執行程式碼。
倉庫
這是一個協程倉庫的示例
interface CoroutineRepository : CoroutineCrudRepository<User, String> {
suspend fun findOne(id: String): User
fun findByFirstname(firstname: String): Flow<User>
suspend fun findAllByFirstname(id: String): List<User>
}
協程倉庫建立在響應式倉庫之上,透過 Kotlin 協程暴露資料訪問的非阻塞特性。協程倉庫上的方法可以由查詢方法或自定義實現支援。如果自定義方法是可 suspend 的,則呼叫自定義實現方法會將協程呼叫傳播到實際的實現方法,而無需實現方法返回響應式型別,例如 Mono 或 Flux。
請注意,根據方法宣告,協程上下文可能可用也可能不可用。要保留對上下文的訪問,要麼使用 suspend 宣告您的方法,要麼返回一個啟用上下文傳播的型別,例如 Flow。
-
suspend fun findOne(id: String): User: 透過掛起一次性同步檢索資料。 -
fun findByFirstname(firstname: String): Flow<User>: 檢索資料流。Flow會立即建立,而資料在Flow互動(Flow.collect(…))時才被獲取。 -
fun getUser(): User: 阻塞執行緒並一次性檢索資料,不進行上下文傳播。應避免這種情況。
只有當倉庫擴充套件 CoroutineCrudRepository 介面時,協程倉庫才會被發現。 |