我有以下代码,无法编译:
import akka.NotUsed
import akka.actor.typed.Behavior
import akka.actor.typed.scaladsl.Behaviors
import akka.pattern.FutureRef
import akka.stream.scaladsl._
import akka.stream.typed.scaladsl.ActorMaterializer
import org.apache.kafka.clients.admin._
import scala.jdk.FutureConverters._
import scala.concurrent.{ExecutionContext, Future}
import scala.concurrent.duration
object KafkaDetectorActor {
val create: Behavior[NotUsed] = Behaviors.setup { context =>
implicit val system = context.system
implicit val materializer = ActorMaterializer()
implicit val dispatcher = context.system.dispatchers
Behaviors.same
}
private def health(server: String)(implicit executor: ExecutionContext): Future[Boolean] = {
val props = new Properties
props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, server)
props.put(AdminClientConfig.CONNECTIONS_MAX_IDLE_MS_CONFIG, "10000")
props.put(AdminClientConfig.REQUEST_TIMEOUT_MS_CONFIG, "5000")
AdminClient
.create(props)
.listTopics()
.names()
.asScala
}
其中names
返回KafkaFuture[java.util.Set[String]]
。
它无法识别asScala
方法。 scala.jdk.FutureConverters._
库已导入。我在做什么错了?
答案 0 :(得分:1)
{{1}上的scala.jdk.FutureConverters
operate,因此请先尝试converting CompletableFuture
至KafkaFuture
,
CompletableFuture
现在我们可以致电 implicit class KafkaFutureToCompletableFuture[T](kafkaFuture: KafkaFuture[T]) {
def toCompletableFuture: CompletableFuture[T] = {
val wrappingFuture = new CompletableFuture[T]
kafkaFuture.whenComplete((value, throwable) => {
if (throwable != null) {
wrappingFuture.completeExceptionally(throwable)
}
else {
wrappingFuture.complete(value)
}
})
wrappingFuture
}
}
。例如,
toCompletableFuture.asScala
输出import scala.jdk.FutureConverters._
KafkaFuture.completedFuture(42).toCompletableFuture.asScala.foreach(println)
。您可以尝试
42