How to limit an Akka Stream to execute and send down one message only once per second?

前端 未结 1 888
悲哀的现实
悲哀的现实 2020-12-19 04:05

I have an Akka Stream and I want the stream to send messages down stream approximately every second.

I tried two ways to solve this problem, the first way was to mak

相关标签:
1条回答
  • 2020-12-19 05:11

    You can either put your elements through the throttling flow, which will back pressure a fast source, or you can use combination of tick and zip.

    The first solution would be like this:

    val veryFastSource =
      Source.fromIterator(() => Iterator.continually(Random.nextLong() % 10000))
    
    val throttlingFlow = Flow[Long].throttle(
      // how many elements do you allow
      elements = 1,
      // in what unit of time
      per = 1.second,
      maximumBurst = 0,
      // you can also set this to Enforcing, but then your
      // stream will collapse if exceeding the number of elements / s
      mode = ThrottleMode.Shaping
    )
    
    veryFastSource.via(throttlingFlow).runWith(Sink.foreach(println))
    

    The second solution would be like this:

    val veryFastSource =
      Source.fromIterator(() => Iterator.continually(Random.nextLong() % 10000))
    
    val tickingSource = Source.tick(1.second, 1.second, 0) 
    
    veryFastSource.zip(tickingSource).map(_._1).runWith(Sink.foreach(println))
    
    0 讨论(0)
提交回复
热议问题