这是用户在 2024-3-28 22:12 为 https://camel.apache.org/manual/route-configuration.html 保存的双语快照页面,由 沉浸式翻译 提供双语支持。了解如何保存?

Route Configuration 路由配置

Camel 3.12 introduces route configuration which is used for separating configurations from the routes. This can be used in situations such as configuring different error handling across a set of routes. In previous versions of Camel this was more cumbersome to do, as you would either have to copy the same configuration to a set of routes or rely on global error handling configuration.
骆驼 3.12 引入了路由配置,用于将配置与路由分离。这可以在配置一组路由的不同错误处理时使用。在以前的骆驼版本中,这样做更加麻烦,因为您要么必须将相同的配置复制到一组路由中,要么依赖全局错误处理配置。

Now you can configure a number of route configurations, and then specify on each route which configuration to use (you can use match by ids, wildcards, and regular expression).
现在您可以配置多个路由配置,然后在每个路由上指定要使用的配置(可以使用 ID、通配符和正则表达式进行匹配)。

The route configuration is supported by all DSL’s, so useable by: Java, XML, Groovy, Kotlin and so forth.
路由配置由所有 DSL 支持,因此可用于:Java、XML、Groovy、Kotlin 等等。

In the route configuration you can setup common strategies for:
在路由配置中,您可以设置常见的策略:

Route Configuration Builder in Java DSL
Java DSL 中的路由配置构建器

With Java DSL you can use RouteConfigurationBuilder to specify the configuration as shown below. The builder is similar to RouteBuilder so its use is familiar.
使用 Java DSL,您可以使用 RouteConfigurationBuilder 来指定如下所示的配置。该构建器与 RouteBuilder 类似,因此使用起来很熟悉。

public class MyJavaErrorHandler extends RouteConfigurationBuilder {

    @Override
    public void configuration() throws Exception {
        routeConfiguration("javaError")
            .onException(Exception.class).handled(true)
            .log("Java WARN: ${exception.message}");
    }
}
The RouteConfigurationBuilder uses configuration as the method where the configuration is coded. This is on purpose not to use the configure method which the regular Java DSL RouteBuilder uses for coding Camel routes.
RouteConfigurationBuilder 使用 configuration 作为编码配置的方法。这是有意为之的,不使用常规 Java DSL RouteBuilder 用于编码 Camel 路由的 configure 方法。

In the example above, then there is only one route configuration which has been assigned the ID javaError. This ID allows us to refer to this configuration later when you want to assign which routes are using the configuration.
在上面的示例中,只有一个路由配置被分配了 ID javaError。这个 ID 允许我们在以后引用这个配置,以确定哪些路由正在使用该配置。

This configuration is a basic configuration that just catches and handles all exceptions and logs a WARN message.
这个配置是一个基本配置,只是捕获和处理所有异常,并记录一个警告信息。

Assigning route configurations to routes
分配路由配置给路由

To use this configuration in your routes, then you can assign it with routeConfigurationId as shown:
要在您的路由中使用此配置,您可以按照所示使用 routeConfigurationId 进行分配

public class MyJavaRouteBuilder extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        from("timer:java?period=2s")
            // refer to the route configuration by the id to use for this route
            .routeConfigurationId("javaError")
            .setBody(method(MyJavaRouteBuilder.class, "randomNumber"))
            .log("Random number ${body}")
            .filter(simple("${body} < 30"))
                .throwException(new IllegalArgumentException("The number is too low"));
    }

    public static int randomNumber() {
        return new Random().nextInt(100);
    }
}

In the routeConfigurationId the configuration to use is specified by the ID, eg javaError.
routeConfigurationId 中,要使用的配置由 ID 指定,例如 javaError。

Multiple configurations can be assigned (separated by comma), such as:
可以分配多个配置(用逗号分隔),例如:

.routeConfigurationId("javaError,myAudit")

The route configurations supports matching by:
路由配置支持以下匹配方式:

  • exact ID name. This is the sample we have seen above.
    确切的 ID 名称。这是我们之前看到的示例。

  • wildcard 通配符

  • regular expression. 正则表达式。

Wildcards are text ending with a *; they are matched when the configuration ID starts with the specified text followed by any characters. For instance, you can do:
通配符是以*结尾的文本;当配置 ID 以指定的文本开头,后面跟任意字符时,它们会匹配。例如,你可以这样做:

.routeConfigurationId("java*,myAudit")

Here we use wildcard in java* which means any configuration whose ID starts with java is a match.
在这里,我们使用 Java*中的通配符,这意味着任何以 java 开头的配置都是匹配的。

Match by regular expression is just like match by wildcard but using regex instead.
使用正则表达式进行匹配就像使用通配符进行匹配一样,只是使用正则表达式而已。

.routeConfigurationId(".*error.*")

Here we want to match any configuration whose ID contains error.
在这里,我们想要匹配任何 ID 中包含错误的配置。

Adding route configurations to CamelContext
将路由配置添加到 CamelContext

Because a RouteConfigurationBuilder is also a RouteBuilder then you add route configurations the same way for RouteBuilder such as using the API on CamelContext
因为 RouteConfigurationBuilder 也是 RouteBuilder ,所以您可以像 RouteBuilder 一样添加路由配置,例如使用 CamelContext 上的 API

CamelContext context = ...
// add the route configuration
context.addRoutes(new MyJavaErrorHandler());
// add the regular route
context.addRoutes(new MyJavaRouteBuilder());

If you use Spring Boot, then your Camel routes and route configurations can be auto-discovered by the spring boot component scanning. This requires adding the @Component annotation to the class.
如果您使用 Spring Boot,那么您的 Camel 路由和路由配置可以通过 Spring Boot 组件扫描自动发现。这需要在类上添加 @Component 注解。

See the example camel-spring-boot-examples/routes-configuration.
请参考示例 camel-spring-boot-examples/routes-configuration。

Route configuration with Endpoint DSL
使用端点 DSL 进行路由配置

The Endpoint DSL can also be used for route configurations. This requires adding camel-endpointdsl to the classpath, and then using org.apache.camel.builder.endpoint.EndpointRouteConfigurationBuilder, which offers the type safe DSL for Camel endpoints.
Endpoint DSL 也可以用于路由配置。这需要将 camel-endpointdsl 添加到类路径中,然后使用 org.apache.camel.builder.endpoint.EndpointRouteConfigurationBuilder ,它为 Camel 端点提供了类型安全的 DSL。

Default route configurations
默认路由配置

Route configurations are either given an explicit unique ID, or the configuration is nameless. A nameless configuration is used as default/fallback configuration, for routes which have NOT been explicitly assigned route configurations.
路由配置要么被赋予一个明确的唯一 ID,要么是无名的。无名配置被用作默认/回退配置,用于那些没有被明确分配路由配置的路由。

Suppose you have one nameless configuration and another named retryError:
假设你有一个无名称的配置和另一个名为 retryError 的配置:

public class MyJavaErrorHandler extends RouteConfigurationBuilder {

    @Override
    public void configuration() throws Exception {
        routeConfiguration()
            .onException(Exception.class).handled(true)
            .log("WARN: ${exception.message}");

        routeConfiguration("retryError")
            .onException(Exception.class).maximumRedeliveries(5);
    }
}

And the following two routes:
以下是两条路线:

   from("file:cheese").routeId("cheese")
        .to("kafka:cheese");

   from("file:beer").routeId("beer")
        .routeConfigurationId("retryError")
        .to("jms:beer");

In the example above, the cheese route has no route configurations assigned, so the route will use the default configuration, which in case of an exception will log a warning.
在上面的示例中,奶酪路由没有分配路由配置,因此该路由将使用默认配置,如果出现异常,将记录一个警告。

The beer route on the other hand has the route configuration retryError assigned, and this configuration will in case of an exception retry up to 5 times and then if still an error then fail and rollback.
另一方面,啤酒路线具有分配的路线配置 retryError,如果出现异常,该配置将重试最多 5 次,如果仍然出错,则失败并回滚。

If you add more routes, then those routes can also be assigned the retryError configuration if they should also retry in case of error.
如果您添加更多的路由,那么这些路由也可以分配 retryError 配置,以便在出现错误时进行重试。

Route Configuration with Error Handler
路由配置与错误处理

Each route configuration can also have a specific error handler configured, as shown below:
每个路由配置也可以配置一个特定的错误处理程序,如下所示:

public class MyJavaErrorHandler extends RouteConfigurationBuilder {

    @Override
    public void configuration() throws Exception {
        routeConfiguration()
            .errorHandler(deadLetterChannel("mock:dead"));

        routeConfiguration("retryError")
            .onException(Exception.class).maximumRedeliveries(5);
    }
}

In the example above, the nameless configuration has an error handler with a dead letter queue. And the route configuration with id retryError does not, and instead it will attempt to retry the failing message up till 5 times before giving up (exhausted). Because this route configuration does not have any error handler assigned, then Camel will use the default error handler.
在上面的示例中,无名配置具有带有死信队列的错误处理程序。而具有 id retryError 的路由配置没有,而是在放弃之前(耗尽)尝试重试失败的消息最多 5 次。因为此路由配置没有分配任何错误处理程序,所以 Camel 将使用默认的错误处理程序。

Routes that have a local error handler defined, will always use this error handler, instead of the error handler from route configurations. A route can only have 1 error handler.
具有本地错误处理程序定义的路由将始终使用该错误处理程序,而不是路由配置中的错误处理程序。一个路由只能有一个错误处理程序。

Route Configuration in XML
XML 中的路由配置

When using XML DSL then you can code your route configurations in XML files as shown below:
使用 XML DSL 时,您可以将路由配置编码到 XML 文件中,如下所示:

<routeConfiguration id="xmlError">
    <onException>
        <exception>java.lang.Exception</exception>
        <handled><constant>true</constant></handled>
        <log message="XML WARN: ${exception.message}"/>
    </onException>
</routeConfiguration>

And in the XML routes you can assign which configurations to use:
在 XML 路由中,您可以指定要使用哪些配置:

<route routeConfigurationId="xmlError">
    <from uri="timer:xml?period=5s"/>
    <log message="I am XML"/>
    <throwException exceptionType="java.lang.Exception" message="Some kind of XML error"/>
</route>

In this example the route is assigned the xmlError route configuration by the exact ID.
在这个例子中,路由被分配了精确的 ID 为 xmlError 的路由配置。

Route Configuration in YAML
YAML 中的路由配置

When using YAML DSL then you can code your route configurations in YAML files as shown below:
当使用 YAML DSL 时,您可以将路由配置编码到 YAML 文件中,如下所示:

- route-configuration:
    id: "yamlError"
    on-exception:
    - on-exception:
        handled:
          constant: "true"
        exception:
          - "java.lang.Exception"
        steps:
          - log:
              message: "YAML WARN ${exception.message}"

And in the YAML routes you can assign which configurations to use:
在 YAML 路由中,您可以指定要使用哪些配置:

- route:
    # refer to the route configuration by the id to use for this route
    route-configuration-id: "yamlError"
    from:
      uri: "timer:yaml?period=3s"
      steps:
        - set-body:
            simple: "Timer fired ${header.CamelTimerCounter} times"
        - to:
            uri: "log:yaml"
            parameters:
              show-body-type: false
              show-exchange-pattern: false
        - throw-exception:
            exception-type: "java.lang.IllegalArgumentException"
            message: "Error from yaml"

In this example the route is assigned the yamlError route configuration by the exact ID.
在这个例子中,路由通过确切的 ID 被分配了 yamlError 路由配置。

Mixing DSLs 混合 DSLS

Routes and route configuration are not required to use the same language. For example, you can code route configurations in Java, and then use XML DSL for the routes, and they would work together.
路由和路由配置不需要使用相同的语言。例如,您可以使用 Java 编写路由配置,然后使用 XML DSL 编写路由,它们可以一起工作。

Route Configuration in classic Spring/Blueprint XML
经典 Spring/Blueprint XML 中的路由配置

When using XML DSL with camel-spring-xml or camel-blueprint then you can code your route configurations in <routeConfigurationContext> snippets in separate XML files as shown below:
当使用带有 camel-spring-xmlcamel-blueprint 的 XML DSL 时,您可以将路由配置编码在单独的 XML 文件中的 <routeConfigurationContext> 片段中,如下所示:

<routeConfigurationContext id="myConf" xmlns="http://camel.apache.org/schema/spring">
    <routeConfiguration id="xmlError">
        <onException>
            <exception>java.lang.Exception</exception>
            <handled><constant>true</constant></handled>
            <log message="XML WARN: ${exception.message}"/>
        </onException>
    </routeConfiguration>
</routeConfigurationContext>

Then from <camelContext> you can refer to these XML snippets by their ids:
然后从 <camelContext> 中,您可以通过它们的 id 引用这些 XML 片段

<camelContext id="myCamel" xmlns="http://camel.apache.org/schema/spring">

    <!-- refer to the ID on the context that has the route configurations (see above) -->
    <routeConfigurationContextRef ref="myConf"/>

    <!-- routes can then assign which configuration to use -->
    <route routeConfigurationId="xmlError">
        <from uri="timer:xml?period=5s"/>
        <log message="I am XML"/>
        <throwException exceptionType="java.lang.Exception" message="Some kind of XML error"/>
    </route>
</camelContext>

In this example the route is assigned the xmlError route configuration by the exact ID.
在这个例子中,路由被分配了精确的 ID 为 xmlError 的路由配置。

Packaging route configurations in reusable JARs
将包装路线配置在可重复使用的罐子中

You can package common route configurations into JARs which you can then use together with your Camel applications, by adding the JARs as dependencies to the classpath (such as in Maven pom.xml file).
您可以将常见的路由配置打包成 JAR 文件,然后将其作为依赖项添加到类路径中(例如在 Maven 的 pom.xml 文件中),以便与您的 Camel 应用程序一起使用。

This allows for example to use a common practice among your Camel applications.
这样就可以例如在您的 Camel 应用程序中使用一种常见的做法。

Logging Summary 日志摘要

If you set startup-summary-level=verbose then Camel will log for each route which route configurations they have been assigned.
如果设置了 startup-summary-level=verbose ,则 Camel 将记录每个路由分配了哪些路由配置。

This option can be configured via Java API and also in application.properties for Camel on Spring Boot, Quarkus, and Camel standalone via camel-main
此选项可以通过 Java API 进行配置,也可以通过 application.properties 在 Spring Boot、Quarkus 和 Camel 独立模式下进行配置,通过 camel-main

camelContext.setStartupSummaryLevel(StartupSummaryLevel.Verbose);

And with Spring Boot:
使用 Spring Boot:

camel.spring-boot.startup-summary-level = verbose

And in Camel Main / Quarkus:
在 Camel Main / Quarkus 中:

camel.main.startup-summary-level = verbose

Route Precondition 路线前提条件

The route configurations can be included or not according to the result of a test expressed in simple language that is evaluated only once during the initialization phase.
路由配置可以根据在初始化阶段仅评估一次的简单语言表达的测试结果来包含或不包含。

In the next example, the route configuration is only included if the parameter activate has been set to true.
在下一个示例中,只有当参数 activate 设置为 true 时,路由配置才会被包含进来。

routeConfiguration().precondition("{{activate}}")
    .onException(IllegalArgumentException.class)
    .handled(true)
    .log("WARN: ${exception.message}");

And the same example using XML DSL:
使用 XML DSL 的相同示例:

<routeConfiguration precondition="{{activate}}">
    <onException>
        <exception>java.lang.IllegalArgumentException</exception>
        <handled>
            <constant>true</constant>
        </handled>
        <log message="XML WARN: ${exception.message}"/>
    </onException>
</routeConfiguration>

And in YAML DSL:
在 YAML DSL 中:

- route-configuration:
    precondition: "{{activate}}"
    on-exception:
    - on-exception:
        exception:
          - "java.lang.IllegalArgumentException"
        handled:
          constant: "true"
        steps:
          - log:
              message: "YAML WARN ${exception.message}"