175.7. 预定义的表达式
从 Camel 版本 2.13.0 开始,JGroups 组件附带了预定义的表达式工厂类,名为 JGroupsExpressions。
如果您要创建仅当 Camel 上下文尚未启动时才会影响路由的 delayer,请使用 JGroupsExpressions.delayIfContextNotStarted (long delay)
factory 方法。只有 Camel 上下文处于与启动不同的状态时,此工厂方法创建的表达式才会返回 given delay 值。如果您希望使用 JGroups 组件在集群中保持单例(master)路由,则此表达式特别有用。如果 Camel 上下文尚未启动,则 控制总线
start
命令不会初始化单例路由。因此,您需要延迟 master 路由的启动,以确保它在 Camel 上下文启动后初始化。由于这种场景只能在集群初始化期间发生,因此我们不希望将从属节点的启动延迟到新主服务器 - 这是我们需要条件延迟表达式的原因。
以下代码片段演示了如何将条件延迟与 JGroups 组件一起使用,以延迟集群中主节点的初始启动。
import static java.util.concurrent.TimeUnit.SECONDS; import static org.apache.camel.component.jgroups.JGroupsExpressions.delayIfContextNotStarted; import static org.apache.camel.component.jgroups.JGroupsFilters.dropNonCoordinatorViews; ... from("jgroups:clusterName?enableViewMessages=true"). filter(dropNonCoordinatorViews()). threads().delay(delayIfContextNotStarted(SECONDS.toMillis(5))). // run in separated and delayed thread. Delay only if the context hasn't been started already. to("controlbus:route?routeId=masterRoute&action=start&async=true"); from("timer://master?repeatCount=1").routeId("masterRoute").autoStartup(false).to(masterMockUri);