8.8. Throttler

概述

throttler 是一个处理器,限制了传入消息的流率。您可以使用此模式来保护目标端点不受过载。在 Apache Camel 中,您可以使用 throttle() Java DSL 命令实施节流模式。

Java DSL 示例

要将流率限制为每秒 100 个消息,请定义路由,如下所示:

from("seda:a").throttle(100).to("seda:b");

如果需要,您可以使用 timePeriodMillis() DSL 命令自定义管理流率的时间段。例如,要将流率限制为每 30000 毫秒的 3 个消息,请按如下所示定义路由:

from("seda:a").throttle(3).timePeriodMillis(30000).to("mock:result");

XML 配置示例

以下示例演示了如何在 XML 中配置前面的路由:

<camelContext id="throttleRoute" xmlns="http://camel.apache.org/schema/spring">
  <route>
    <from uri="seda:a"/>
    <!-- throttle 3 messages per 30 sec -->
    <throttle timePeriodMillis="30000">
      <constant>3</constant>
      <to uri="mock:result"/>
    </throttle>
  </route>
</camelContext>

动态更改每个期间的最大请求

可用的 Camel 2.8 Since 使用 Expression,您可以在运行时调整这个值,例如,为标头提供值。运行时 Camel 评估表达式并将结果转换为 java.lang.Long 类型。在以下示例中,我们使用邮件中的标头来决定每个期间的最大请求。如果缺少标头,则 第 8.8 节 “Throttler” 使用旧值。因此,在要更改值时,只允许提供标头:

<camelContext id="throttleRoute" xmlns="http://camel.apache.org/schema/spring">
  <route>
    <from uri="direct:expressionHeader"/>
    <throttle timePeriodMillis="500">
      <!-- use a header to determine how many messages to throttle per 0.5 sec -->
      <header>throttleValue</header>
      <to uri="mock:result"/>
    </throttle>
  </route>
</camelContext>

异步延迟

throttler 可以启用 非阻塞异步延迟,这意味着 Apache Camel 将计划以后要执行的任务。该任务负责处理路由的后方(throttler 后)。这允许调用器线程取消阻塞和服务进一步传入的信息。例如:

from("seda:a").throttle(100).asyncDelayed().to("seda:b");
注意

从 Camel 2.17 中,Throttler 将使用滚动窗口进行时间,以便更好地处理消息。但是,它将提高节流的性能。

选项

throttle DSL 命令支持以下选项:

名称

默认值

描述

maximumRequestsPerPeriod

 

节流时的最大请求数。必须提供这个选项和正数。注意在 XML DSL 中,从 Camel 2.8 开始使用此选项时,使用 Expression 而不是属性来配置。

timePeriodMillis

1000

millis 中的时间周期,在 millis 中,节流允许 最多允许最大RequestsPerPeriod 的消息数。

asyncDelayed

false

Camel 2.4: 如果启用,则任何使用调度的线程池延迟的消息都会进行。

executorServiceRef

 

Camel 2.4: 如果已启用 asyncDelay,请参阅使用自定义线程池。

callerRunsWhenRejected

true

Camel 2.4: 如果启用了 asyncDelayed,则会使用它。这将控制在线程池中拒绝该任务时调用器线程是否应该执行该任务。