我有示例代码来生成未绑定的源并使用它:
对象Main {
def main(args : Array[String]): Unit = {
implicit val system = ActorSystem("Sys")
import system.dispatcher
implicit val materializer = ActorFlowMaterializer()
val source: Source[String] = Source(() => {
Iterator.continually({ "message:" + ThreadLocalRandom.current().nextInt(10000)})
})
source.runForeach((item:String) => { println(item) })
.onComplete{ _ => system.shutdown() }
}
}
我想创建实现的类:
trait MySources {
def addToSource(item: String)
def getSource() : Source[String]
}
我需要在多个线程中使用它,例如:
class MyThread(mySources: MySources) extends Thread {
override def run(): Unit = {
for(i <- 1 to 1000000) { // here will be infinite loop
mySources.addToSource(i.toString)
}
}
}
预计完整代码:
object Main {
def main(args : Array[String]): Unit = {
implicit val system = ActorSystem("Sys")
import system.dispatcher
implicit val materializer = ActorFlowMaterializer()
val sources = new MySourcesImplementation()
for(i <- 1 to 100) {
(new MyThread(sources)).start()
}
val source = sources.getSource()
source.runForeach((item:String) => { println(item) })
.onComplete{ _ => system.shutdown() }
}
}
如何实施MySources
?
答案 0 :(得分:19)
拥有非限定源的一种方法是使用特殊类型的actor作为源,混合在ActorPublisher
特征中。如果您创建其中一种演员,然后打电话给ActorPublisher.apply
,最终会得到一个Reactive Streams Publisher
实例,您可以使用apply
Source
从中生成Source
。之后,您只需确保您的ActorPublisher
类正确处理Reactive Streams协议,以便向下游发送元素,您就可以开始使用了。一个非常简单的例子如下:
import akka.actor._
import akka.stream.actor._
import akka.stream.ActorFlowMaterializer
import akka.stream.scaladsl._
object DynamicSourceExample extends App{
implicit val system = ActorSystem("test")
implicit val materializer = ActorFlowMaterializer()
val actorRef = system.actorOf(Props[ActorBasedSource])
val pub = ActorPublisher[Int](actorRef)
Source(pub).
map(_ * 2).
runWith(Sink.foreach(println))
for(i <- 1 until 20){
actorRef ! i.toString
Thread.sleep(1000)
}
}
class ActorBasedSource extends Actor with ActorPublisher[Int]{
import ActorPublisherMessage._
var items:List[Int] = List.empty
def receive = {
case s:String =>
if (totalDemand == 0)
items = items :+ s.toInt
else
onNext(s.toInt)
case Request(demand) =>
if (demand > items.size){
items foreach (onNext)
items = List.empty
}
else{
val (send, keep) = items.splitAt(demand.toInt)
items = keep
send foreach (onNext)
}
case other =>
println(s"got other $other")
}
}
答案 1 :(得分:11)
使用Akka Streams 2,您可以使用sourceQueue:How to create a Source that can receive elements later via a method call?
答案 2 :(得分:0)
正如我在this answer中提到的那样,SourceQueue
是必经之路,并且由于Akka 2.5,因此有一种方便的方法preMaterialize
,该方法无需先创建复合源。
我在other answer中举了一个例子。