将回调方法实现转换为akka流源

时间:2015-04-03 16:47:10

标签: scala akka akka-stream

我正在使用我无法控制的java库中的数据发布者。发布商库使用典型的回调设置;库代码中的某个地方(库是java,但我将在scala中描述为简洁性):

type DataType = ???

trait DataConsumer {
  def onData(data : DataType) : Unit
}

库的用户需要编写一个实现onData方法的类并将其传递给DataProducer,库代码如下所示:

class DataProducer(consumer : DataConsumer) {...}

DataProducer有自己无法控制的内部线程,以及伴随的数据缓冲区,只要有另一个onData对象要消耗,就会调用DataType

所以,我的问题是:如何编写一个将原始库模式转换/转换为akka流Source对象的图层?

提前谢谢你。

2 个答案:

答案 0 :(得分:5)

回调 - >来源

详细说明Endre Varga的答案,下面是将创建DataConsumer回调函数的代码,该函数将消息发送到akka流Source

警告:创建一个有效的ActorPublish比我在下面指出的要多得多。特别是,需要进行缓冲以处理DataProducer调用onData的速度超过Sink信令需求的情况(请参阅此example)。下面的代码只是设置了“接线”。

import akka.actor.ActorRef
import akka.actor.Actor.noSender

import akka.stream.Actor.ActorPublisher

/**Incomplete ActorPublisher, see the example link.*/
class SourceActor extends ActorPublisher[DataType] {
  def receive : Receive = {
    case message : DataType => deliverBuf() //defined in example link
  }    
}

class ActorConsumer(sourceActor : ActorRef) extends DataConsumer {
  override def onData(data : DataType) = sourceActor.tell(data, noSender)
}

//setup the actor that will feed the stream Source
val sourceActorRef = actorFactory actorOf Props[SourceActor]

//setup the Consumer object that will feed the Actor
val actorConsumer = ActorConsumer(sourceActorRef)

//setup the akka stream Source
val source = Source(ActorPublisher[DataType](sourceActorRef))

//setup the incoming data feed from 3rd party library
val dataProducer  = DataProducer(actorConsumer)

回调 - >整个流

原始问题专门针对Source回调,但如果整个流已经可用(不仅仅是Source),处理回调更容易处理。这是因为可以使用Source#actorRef函数将流实现为ActorRef。举个例子:

val overflowStrategy = akka.stream.OverflowStrategy.dropHead

val bufferSize = 100

val streamRef = 
  Source
    .actorRef[DataType](bufferSize, overflowStrategy)
    .via(someFlow)
    .to(someSink)
    .run()

val streamConsumer = new DataConsumer {
  override def onData(data : DataType) : Unit = streamRef ! data
} 

val dataProducer = DataProducer(streamConsumer)

答案 1 :(得分:1)

有多种方法可以解决这个问题。一种是使用ActorPublisher:http://doc.akka.io/docs/akka-stream-and-http-experimental/1.0-M5/scala/stream-integrations.html#Integrating_with_Actors,您可以在其中更改回调,以便它向actor发送消息。根据回调的工作方式,您也可以使用mapAsync(将回调转换为Future)。只有在一个请求产生一个回调调用时,这才有效。