![](/img/trans.png)
[英]Accessing the underlying ActorRef of an akka stream Source created by Source.actorRef
[英]Sink fold for akka stream Source.actorRef buffer and OverflowStrategy
這是akka文檔中的代碼片段
val sinkUnderTest = Flow[Int].map(_.toString).toMat(Sink.fold("")(_ + _))(Keep.right)
val (ref, future) = Source.actorRef(3, OverflowStrategy.fail)
.toMat(sinkUnderTest)(Keep.both).run()
ref ! 1
ref ! 2
ref ! 3
ref ! akka.actor.Status.Success("done")
val result = Await.result(future, 3.seconds)
assert(result == "123")
這是一個工作代碼段,但是,如果我使用ref告訴另一個消息,例如ref ! 4
ref ! 4
,我遇到了一個類似akka.stream.BufferOverflowException: Buffer overflow (max capacity was: 3)
的異常akka.stream.BufferOverflowException: Buffer overflow (max capacity was: 3)
我猜緩沖區大小3應該足夠了。 折疊操作的原因是(acc,ele)=> acc,因此需要累加器和元素返回新值累加器。
因此,我更改了代碼,讓另一個演員告訴他等待3秒鍾。 並且它再次起作用。
val sinkUnderTest = Flow[Int].map(_.toString).toMat(Sink.fold("")(_ + _))(Keep.right)
private val (ref, future): (ActorRef, Future[String]) = Source.actorRef(3, OverflowStrategy.backpressure).toMat(sinkUnderTest)(Keep.both).run()
ref ! 1
ref ! 2
ref ! 3
Thread.sleep(3000)
ref ! 4
ref ! akka.actor.Status.Success("done")
val result = Await.result(future, 10.seconds)
println(result)
但是,我的問題是,有沒有一種方法可以告訴Akka流減慢速度或等待接收器可用。 我還使用了OverflowStrategy.backpressure
,但是它Backpressure overflowStrategy not supported
。
還有其他選擇嗎?
您應該查看Source.queue
,以一種以感知背壓的方式從外部將元素注入流中的方法。
Source.queue
將Source.queue
可以向其提供元素的隊列對象,但是,當您提供它們時,您將獲得一個Future
,該流在流准備好接受消息時完成。
下面的例子:
val sinkUnderTest = Flow[Int].map(_.toString).toMat(Sink.fold("")(_ + _))(Keep.right)
val (queue, future): (SourceQueueWithComplete[Int], Future[String]) =
Source.queue(3, OverflowStrategy.backpressure).toMat(sinkUnderTest)(Keep.both).run()
Future.sequence(Seq(
queue.offer(1),
queue.offer(2),
queue.offer(3),
queue.offer(4)
))
queue.complete()
val result = Await.result(future, 10.seconds)
println(result)
在文檔中有更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.