gpt4 book ai didi

mongodb - MongoDB observeOn 为什么不使用指定的执行上下文?

转载 作者:可可西里 更新时间:2023-11-01 10:46:21 27 4
gpt4 key购买 nike

在 Scala 中,我编写了两个 MongoDB 可观察对象,并在传递自定义执行上下文时调用了 observeOn。在第一个可观察对象上调用 observeOn,但自定义执行上下文不会传播到第二个可观察对象。

为了帮助说明这一点,我编写了以下自包含代码:

import java.util.concurrent.{LinkedBlockingQueue, ThreadPoolExecutor, TimeUnit}

import org.apache.commons.lang3.concurrent.BasicThreadFactory.Builder
import org.mongodb.scala.bson.collection.immutable.Document
import org.mongodb.scala.{MongoClient, Observable}

import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext}

object Test extends App {

val client = MongoClient("mongodb://localhost")

def insertObs = {
client.getDatabase("test").getCollection("test").insertOne(Document("test" -> 1))
}

val threadPool = new ThreadPoolExecutor(2, 2, 0L,
TimeUnit.MILLISECONDS, new LinkedBlockingQueue[Runnable],
new Builder().namingPattern("Custom pool").build())
val executionContext = ExecutionContext fromExecutor (threadPool)

val obs = Observable(List(1, 2, 3))
val res =
obs.observeOn(executionContext).map {
i =>
println("OBS " + Thread.currentThread().getName)
i
}.flatMap(_ => insertObs.map {
i =>
println("INSERT " + Thread.currentThread().getName)
i
})
Await.result(res.toFuture(), Duration(20, TimeUnit.SECONDS))
}

输出如下:

OBS Custom pool
INSERT Thread-2
OBS Custom pool
INSERT Thread-2
OBS Custom pool
INSERT Thread-4

在执行“INSERT”可观察对象时,我只希望将“自定义池”用作执行上下文,而不是使用 Thread-2 和 Thread-4。如此处文档中所述:

MongoDB observeOn API

具体来说,它说:为 future 的操作使用特定的执行上下文

为什么自定义线程池不用于“插入”可观察对象?

最佳答案

这似乎按预期工作:查看这张票:https://jira.mongodb.org/browse/SCALA-437

关于mongodb - MongoDB observeOn 为什么不使用指定的执行上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51560998/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com