如何在Akka Streams中计算GraphStage内的聚合?

rn0zuynd  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(139)

我在Akka流中有一个运算符/组件,它的目标是在5秒内计算一个值。因此,我使用TimerGraphStageLogic创建了我的运算符/组件,您可以在下面的代码中看到。为了测试它,我创建了2个源,一个递增,另一个递减,然后我使用Merge形状合并它们,然后我使用我的windowFlowShape,最后以Sink的形式发出它们。我确保TimerGraphStageLogic工作正常,因为我在另一个PoC中测试过它。在本例中,我只是将泛型类型T替换为Int,因为我必须指定窗口将聚合什么。
但是,我的问题是我无法在窗口阶段操作符内聚合Int值。当我尝试执行sum = sum + elem时,我在运行时收到一个错误,内容如下:

overloaded method value + with alternatives:
  (x: scala.Int)scala.Int <and>
  (x: Char)scala.Int <and>
  (x: Short)scala.Int <and>
  (x: Byte)scala.Int
 cannot be applied to (Int(in class WindowProcessingTimerFlow))
                sum = sum + elem

下面是我的代码,它编译但在运行时抛出上述错误:

import akka.actor.ActorSystem
import akka.stream._
import akka.stream.scaladsl.{Flow, GraphDSL, Merge, RunnableGraph, Sink, Source}
import akka.stream.stage._
import scala.collection.mutable
import scala.concurrent.duration._

object StreamOpenGraphWindow {
  def main(args: Array[String]): Unit = {
    run()
  }
  def run() = {
    implicit val system = ActorSystem("StreamOpenGraphWindow")
    val sourceNegative = Source(Stream.from(0, -1)).throttle(1, 1 second)
    val sourcePositive = Source(Stream.from(0)).throttle(1, 1 second)

    // Step 1 - setting up the fundamental for a stream graph
    val windowRunnableGraph = RunnableGraph.fromGraph(
      GraphDSL.create() { implicit builder =>
        import GraphDSL.Implicits._
        // Step 2 - create shapes
        val mergeShape = builder.add(Merge[Int](2))
        val windowFlow = Flow.fromGraph(new WindowProcessingTimerFlow[Int](5 seconds))
        val windowFlowShape = builder.add(windowFlow)
        val sinkShape = builder.add(Sink.foreach[Int](x => println(s"sink: $x")))

        // Step 3 - tying up the components
        sourceNegative ~> mergeShape.in(0)
        sourcePositive ~> mergeShape.in(1)
        mergeShape.out ~> windowFlowShape ~> sinkShape

        // Step 4 - return the shape
        ClosedShape
      }
    )
    // run the graph and materialize it
    val graph = windowRunnableGraph.run()
  }

  // step 0: define the shape
  class WindowProcessingTimerFlow[Int](silencePeriod: FiniteDuration) extends GraphStage[FlowShape[Int, Int]] {
    // step 1: define the ports and the component-specific members
    val in = Inlet[Int]("WindowProcessingTimerFlow.in")
    val out = Outlet[Int]("WindowProcessingTimerFlow.out")

    // step 3: create the logic
    override def createLogic(inheritedAttributes: Attributes): GraphStageLogic = new TimerGraphStageLogic(shape) {
      // mutable state
      val batch = new mutable.Queue[Int]
      var open = false

      // step 4: define mutable state implement my logic here
      setHandler(in, new InHandler {
        override def onPush(): Unit = {
          try {
            val nextElement = grab(in)
            batch.enqueue(nextElement)
            if (open) {
              pull(in) // send demand upstream signal, asking for another element
            } else {
              var sum: scala.Int = 0
              val set: Iterable[Int] = batch.dequeueAll(_ => true).to[collection.immutable.Iterable]
              set.toList.foreach { elem =>
                sum = sum + elem //*************WHY I CANNOT DO IT?*************
              }
              push(out, sum)
              open = true
              scheduleOnce(None, silencePeriod)
            }
          } catch {
            case e: Throwable => failStage(e)
          }
        }
      })
      setHandler(out, new OutHandler {
        override def onPull(): Unit = {
          pull(in)
        }
      })
      override protected def onTimer(timerKey: Any): Unit = {
        open = false
      }
    }
    // step 2: construct a new shape
    override def shape: FlowShape[Int, Int] = FlowShape[Int, Int](in, out)
  }
}
7kqas0il

7kqas0il1#

因为您要建立名为Int的型别参数,它会遮蔽型别Int定义,其中定义:

class WindowProcessingTimerFlow[Int](silencePeriod: FiniteDuration) extends GraphStage[FlowShape[Int, Int]] {

尝试从中移除类属:

class WindowProcessingTimerFlow(silencePeriod: FiniteDuration) extends GraphStage[FlowShape[Int, Int]] {

相关问题