59.5. 多个 Camel 上下文
如上所述,可以在应用程序中声明任意数量的 CamelContext
Bean。在这种情况下,CDI 限定符在 CamelContext
beans上声明,用于将 Camel 路由和其他 Camel 原语绑定到对应的 Camel 上下文。从示例中,如果声明了以下 Bean:
@ApplicationScoped @ContextName("foo") class FooCamelContext extends DefaultCamelContext { } @ApplicationScoped @BarContextQualifier class BarCamelContext extends DefaultCamelContext { } @ContextName("foo") class RouteAddedToFooCamelContext extends RouteBuilder { @Override public void configure() { // ... } } @BarContextQualifier class RouteAddedToBarCamelContext extends RouteBuilder { @Override public void configure() { // ... } } @ContextName("baz") class RouteAddedToBazCamelContext extends RouteBuilder { @Override public void configure() { // ... } } @MyOtherQualifier class RouteNotAddedToAnyCamelContext extends RouteBuilder { @Override public void configure() { // ... } }
通过 @ContextName
限定的 RoutesBuilder
Bean 会自动添加到 CamelContext
beans (Camel CDI)中。如果没有这样的 CamelContext
bean,它会被自动创建,如 RouteAddedToBazCamelContext
bean。请注意,这仅适用于 Camel CDI 提供的 @ContextName
限定符。因此, RouteNotAddedToAnyCamelContext
与用户定义的 @MyOtherQualifier
限定符不会添加到任何 Camel 上下文。这可能会很有用,例如,对于稍后在应用程序执行期间可能需要添加的 Camel 路由。
自 Camel 版本 2.17.0 起,Camel CDI 能够管理任何类型的 CamelContext
Bean (例如 DefaultCamelContext
)。在以前的版本中,它只能够管理类型为 CdiCamelContext
的 Bean,因此需要扩展它。
CamelContext
Bean 上声明的 CDI 限定符也用于绑定相应的 Camel 原语,例如:
@Inject @ContextName("foo") @Uri("direct:inbound") ProducerTemplate producerTemplate; @Inject @ContextName("foo") @Uri("direct:inbound") FluentProducerTemplate fluentProducerTemplate; @Inject @BarContextQualifier MockEndpoint outbound; // URI defaults to the member name, i.e. mock:outbound @Inject @ContextName("baz") @Uri("direct:inbound") Endpoint endpoint;