簡體   English   中英

如何在 java 反應式中為通量 / mono 調用多個服務?

[英]How to invoke multiple services for a flux / mono in java reactive?

我是響應式世界的新手,聽起來可能是新手,我有一系列大小為 20-30 的產品,對於每種產品,我需要從不同的微服務中獲取以下內容:

  1. 平均評論數
  2. 總評論數
  3. 願望清單
  4. 變種..
  5. .. 6..

我試過的..

1.doOnNext

Flux<Product> products = ...
products
.doOnNext(product -> updateReviewCount)
.doOnNext(product -> updateTotalCommentCount)
.doOnNext(product -> updateWishlistedCount)
.doOnNext(product -> updateVariants)
...

事實證明,每個產品的每次調用都會阻塞鏈..

e.g.
Total records(20) * No. of service calls(5) * Time per service calls(30 ms) = 3000ms 

但是時間會隨着記錄的數量而增長|| 服務調用次數。

2. map使用 map 我更新並返回相同的參考,但結果相同。

3.收集所有作為列表並對下游服務執行聚合查詢

Flux<Product> products = ...
products
.collectList() // Mono<List<Product>>
.doOnNext(productList -> updateReviewCountOfAllInList)
.doOnNext(productList -> updateFieldB_ForAllInList)
.doOnNext(productList -> updateFieldC_ForAllInList)
.doOnNext(productList -> updateFieldD_ForAllInList)
...

這確實提高了性能,盡管現在下游應用程序必須為查詢返回更多數據,所以下游端增加的時間很少,但這沒關系。

現在有了這個,我能夠實現如下時間......總記錄(合並為列表,所以 1)* 服務調用次數(5)* 每次服務調用的時間(隨着時間的增加 50 毫秒)= 250 毫秒

但是時間會隨着服務調用的數量而增長。

現在我需要並行化這些服務調用並並行執行這些服務調用,並在同一個產品實例上更新它們各自的字段(相同的引用)。 有些像下面

Flux<Product> products = ... // of 10 products
products
.collectList() // Mono<List<Product>>
.doAllInParallel(serviceCall1, serviceCall2, serviceCall3...)

. // get all updated products // flux size of 10

有了這個我想達到時間...... 250/5 = 50ms

如何做到這一點? 我發現了不同的文章,但我不確定最好的方法是什么? 有人可以幫助我嗎?

它使用

products // Flux<Product>
.collectList() // Mono<List<Product>>
.flatMap(list -> Mono.zip( this.call1(list) ,this.call2(list) ) ) // will return Tuple
.map(t -> t.getT1) 
.flatMapIterable(i->i)

Mono<Product> call1(List<Product> productList){
   // some logic
}
Mono<Product> call2(List<Product> productList){
   // some logic
}

實際上 zip 和 flatmapiterable,所有這些都可以一步完成。這里只是為了演示。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM