協程
依賴項
當 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 到協程 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>
}
協程 repositories 構建在響應式 repositories 之上,透過 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 介面時,才會發現協程 repositories。 |