油门形状的参数是什么意思?

马里奥·加里奇(Mario Galic)

zio-streams提供throttleShape

  /**
   * Delays the chunks of this stream according to the given bandwidth parameters using the token bucket
   * algorithm. Allows for burst in the processing of elements by allowing the token bucket to accumulate
   * tokens up to a `units + burst` threshold. The weight of each chunk is determined by the `costFn`
   * function.
   */
  final def throttleShape(units: Long, duration: Duration, burst: Long = 0)(
    costFn: Chunk[O] => Long
  ): ZStream[R with Clock, E, O]

我在努力了解这些参数unitduration burst并且costFun是为了使用。从我对令牌桶的阅读中

throttleShape(1, 1.second)(_ => 1)

表示处理一个元素需要花费一个令牌(costFun = _ => 1),并且unit = 1在一秒钟(duration = 1.second之后补充一个令牌)。但是,除以下各项外,我使用各种值进行的实验似乎不会产生任何节流作用

throttleShape(1, 1.second)(_ => 2)

这使其挂起。例如,如何解释以下使用无限持续时间的片段(来自PR)的节流

Stream(1, 2, 3, 4)
  .throttleShape(1, Duration.Infinity)(_ => 0)
  .runCollect

Stream(1, 2, 3, 4)
  .throttleShape(2, Duration.Infinity)(_ => 1)
  .take(2)
  .runCollect

具体来说,假设我想每分钟最多处理100个元素,那么应该如何throttleShape指定呢?

阿尔特姆·索科洛夫(Artem Sokolov)

问题在于您的初始流是单个的,Chunk[Int]并且throttleShape如注释中所述-您按块而不是按元素来限制。

构造单个块是Stream(1, 2, 3, 4)因为它对应于

  /**
   * Creates a pure stream from a variable list of values
   */
  def apply[A](as: A*): ZStream[Any, Nothing, A] = fromIterable(as)

在其中

  /**
   * Creates a stream from an iterable collection of values
   */
  def fromIterable[O](as: => Iterable[O]): ZStream[Any, Nothing, O] =
    fromChunk(Chunk.fromIterable(as))

因此,如果要按元素限制,则应将块重新缩放为1个元素.chunkN(1)您应该在节流之前这样做。

所以在

说我想每分钟最多处理100个元素

如果您不需要块的优化(以批量/块方式处理项目),则可以将块缩放为1,然后 throttleShape(100, 1.minute)(_ => 1)

stream.Stream.fromIterable(1 to 1000)
  .chunkN(1)
  .throttleShape(100, 1.minute)(_ => 1)
  .foreachChunk(chunk => console.putStrLn(s"processed '${chunk.foldLeft("")(_ + _)}'"))

或者,如果你想在过程块,并保持相同的处理速度-你可以写costFn_.size

stream.Stream.fromIterable(1 to 1000)
  .chunkN(5)
  .throttleShape(100, 1.minute)(_.size)
  .foreachChunk(chunk => console.putStrLn(s"processed '${chunk.foldLeft("")(_ + _)}'"))

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章