搜索

8.8. Throttler

download PDF

概述

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 的可用 os 使用 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 命令支持以下选项:

Name

默认值

描述

maximumRequestsPerPeriod

 

每个 period 到 throttle 的最大请求数。必须提供这个选项,并有一个正数。请注意,在 XML DSL 中,来自 Camel 2.8 onwards 此选项使用 Expression 而不是属性进行配置。

timePeriodMillis

1000

millis 中的时间段,throttler 将允许最多 maximumRequestsPerPeriod 的消息数。

asyncDelayed

false

Camel 2.4: 如果启用,则使用调度线程池异步发生的任何消息。

executorServiceRef

 

Camel 2.4: 如果启用了 asyncDelay,则引用使用自定义线程池。

callerRunsWhenRejected

true

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

Red Hat logoGithubRedditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

© 2024 Red Hat, Inc.