简体   繁体   English

如何从类内部使递归akka流“可切换”

[英]How to make recursive akka stream 'toggleable' from inside class

I have a class with endless stream that defined as follows: 我有一个具有无限流的类,其定义如下:

abstract class StreamWrapper() {

  def doStuff: Future[Unit] = ???

  def recursiveStream(): Unit =
    events.mapAsync(parallelism)(doStuff)
      .runWith(Sink.fold(???))
      .onComplete( 
        actorSystem.scheduler.scheduleOnce(delay)(recursiveStream())
                                               // ^-- recursion --^
      )

}

I wan't to be able to turn off/on this stream from doStuff function (in my case I have a circuit breaker inside, so I want to turn on/off recursiveStream via it's callbacks). 我将无法通过doStuff函数关闭/打开此流(在我的情况下,我内部有一个断路器,因此我想通过其回调打开/关闭recursiveStream)。

Easiest way to solve this to introduce atomic boolean, check it in recursiveStream method and toggle it inside doStuff : 解决此问题的最简单方法是引入原子布尔,在recursiveStream方法中对其进行检查并在doStuff内部进行切换:

abstract class StreamWrapper() {

  private val enabled = new AtomicBoolean(true)

  def doStuff: Future[Unit] = ??? // toggle enabled here

  def recursiveStream(): Unit = 
    if (enabled)
      events.mapAsync(parallelism)(doStuff)
        .runWith(Sink.fold(???))
        .onComplete( 
          actorSystem.scheduler.scheduleOnce(delay)(recursiveStream())
        )
    else log.info("Stream is currently offline...")

}

But it feels like there are may be more idiomatic solution to do it using Scala and/or Akka features. 但是,感觉使用Scala和/或Akka功能可能会有更多惯用的解决方案。 Can you suggest another method to solve this problem? 您可以提出另一种解决此问题的方法吗?

Use Valve from the Akka Streams Contrib project : 使用来自Akka Streams Contrib项目的 Valve

Materializes into a Future of ValveSwitch which provides a the method flip that stops or restarts the flow of elements passing through the stage. 体现在ValveSwitch的未来中,它提供了一种方法翻转,该方法翻转可停止或重新启动通过阶段的元素流。 As long as the valve is closed it will backpressure. 只要关闭阀门,它就会背压。

Examples of its use are found in ValveSpec . ValveSpec可以找到其用法ValveSpec

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM