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

Java DSL 示例
以下示例演示了如何从 endpoint ( seda:a
, 到 endpoint, seda:b
创建一个路由,它会阻止 foo
标头具有值、bar
的消息以外的所有消息:
RouteBuilder builder = new RouteBuilder() { public void configure() { from("seda:a").filter(header("foo").isEqualTo("bar")).to("seda:b"); } };
RouteBuilder builder = new RouteBuilder() {
public void configure() {
from("seda:a").filter(header("foo").isEqualTo("bar")).to("seda:b");
}
};
要评估更复杂的过滤器 predicates,您可以调用其中一个支持的脚本语言,如 XPath、XQuery 或 SQL (请参阅 第 II 部分 “路由表达式和 predicates 语言”)。以下示例定义了一个路由,用于阻止所有消息,但那些包含 name 属性的 person
元素外,其 name
属性等于 : :
from("direct:start"). filter().xpath("/person[@name='James']"). to("mock:result");
from("direct:start").
filter().xpath("/person[@name='James']").
to("mock:result");
XML 配置示例
以下示例演示了如何在 XML 中使用 XPath predicate 配置路由(请参阅 第 II 部分 “路由表达式和 predicates 语言”):
<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>
<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"); } }
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 中停止进一步处理时,stop 方便在 基于内容的路由器 中使用。
在以下示例中,我们不希望消息正文中带有单词 Bye
的消息来进一步传播路由中的任何内容。我们在使用 .stop ()
的 when ()
predicate 中防止出现这种情况。
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");
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");
了解交换是否被过滤
从 Camel 2.5 开始提供
消息过滤器 EIP 将在 Exchange 中添加属性,如果被过滤或未过滤,则状态。
属性具有键 Exchange.FILTER_MATCHED
,其 String 值为 CamelFilterMatched
。其值是一个布尔值,表示 true
或 false
。如果值为 true
,则在过滤块中路由 Exchange。