8.2. Message Filter
概述
消息过滤器 是一个处理器,用于根据特定标准消除不需要的消息。在 Apache Camel 中,消息过滤器特征(如 图 8.2 “消息过滤器模式” )通过 filter()
Java DSL 命令实现。filter()
命令使用一个控制过滤器的 predicate 参数。当 predicate 为 true
时,允许传入的信息继续,如果 predicate 为 false
,则会阻断传入的信息。
图 8.2. 消息过滤器模式

Java DSL 示例
以下示例演示了如何从端点( seda:a
)创建路由到端点, seda:b
,它将阻断除 foo
标头具有值、bar
的消息之外的所有消息:
RouteBuilder builder = new RouteBuilder() { public void configure() { from("seda:a").filter(header("foo").isEqualTo("bar")).to("seda:b"); } };
要评估更复杂的过滤器 predicates,您可以调用其中一个受支持的脚本语言,如 XPath、XQuery 或 SQL(请参阅 第 II 部分 “路由表达式和指定语言”)。以下示例定义了一个路由,它阻止所有包含 name
属性等于 James
的个人元素外的所有消息:
from("direct:start"). filter().xpath("/person[@name='James']"). to("mock:result");
XML 配置示例
以下示例演示了如何使用 XML 中的 XPath predicate 配置路由(请参阅 第 II 部分 “路由表达式和指定语言”):
<camelContext id="simpleFilterRoute" xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="seda:a"/> <filter> <xpath>$foo = 'bar'</xpath> <to uri="seda:b"/> </filter> </route> </camelContext>
在关闭 </filter> 标签前,确保您将要过滤的端点(例如,< ;to uri="seda:b"
/>),或者过滤器不会被应用(在 2.8+ 中,省略此操作会导致错误)。
使用 Bean 过滤
以下是使用 bean 定义过滤器行为的示例:
from("direct:start") .filter().method(MyBean.class, "isGoldCustomer").to("mock:result").end() .to("mock:end"); public static class MyBean { public boolean isGoldCustomer(@Header("level") String level) { return level.equals("gold"); } }
使用 stop()
可作为 Camel 2.0 提供
stop 是过滤 所有消息的 特殊过滤器。当您需要在其中一个 predicates 中停止进一步处理时,停止便可在 基于内容的路由器 中使用。
在以下示例中,我们不需要在邮件正文中传递单词的消息,以便在路由中进一步传播信息。我们防止在
when()
predicate 中使用 .stop()
。
from("direct:start")
.choice()
.when(bodyAs(String.class).contains("Hello")).to("mock:hello")
.when(bodyAs(String.class).contains("Bye")).to("mock:bye").stop()
.otherwise().to("mock:other")
.end()
.to("mock:result");
了解是否过滤 Exchange
可作为 Camel 2.5 提供。
消息过滤器 EIP 将添加 Exchange 的属性,该属性将说明(如果已过滤或未过滤)。
该属性具有关键 Exchange.FILTER_MATCHED
,其字符串值为 CamelFilterMatched
。其值是一个布尔值,代表 true
或 false
。如果值为 true
,则在 filter 块中路由 Exchange。