部署到 Spring Boot


Red Hat Fuse 7.5

在独立模式中构建并运行 Spring Boot 应用程序

Fuse Documentation Team

摘要

本指南介绍了如何构建作为 Jar 文件打包的 Spring Boot 应用程序,并直接以 JVM (单机模式)运行。

第 1 章 Spring Boot 独立入门

1.1. 关于 Spring Boot 独立部署模式

在单机部署模式中,Spring Boot 应用被打包为 Jar 文件,直接在 Java 虚拟机(JVM)中运行。也就是说,Spring Boot 应用程序可以使用 java 命令直接运行,并带有 -jar 选项的 -jar 选项,例如:

java -jar SpringBootApplication.jar
Copy to Clipboard Toggle word wrap

其中 Spring Boot 为可执行 Jar 提供主类。

此方法打包和运行应用与微服务理念一致,其中服务打包了最低要求。容器也是最小的,只是 JVM 本身。

在 Fuse 中构建 Spring Boot 独立应用程序需要以下元素:

  • Fuse Bill of Materials (BOM) mvapich-进行了从 Red Hat Maven 存储库完全策展的依赖关系集合。BOM 利用 Maven 的依赖项管理机制 来定义适当的 Maven 依赖项版本。

    请注意,红帽只支持 Fuse BOM 中定义的依赖项。

  • Spring Boot Maven 插件实现 Maven 中 独立 Spring Boot 应用程序的构建过程。此插件负责将 Spring Boot 应用程序打包为可执行 Jar 文件。

1.1.1. 部署到 Spring Boot 2

除了 Spring Boot 1 外,您还可以选择部署到 Spring Boot 2 中。

注意

如需有关 OpenShift 部署模式的详细信息,请参阅 OpenShift 上的 Fuse 指南

注意

有关 Spring Boot 1 和 Spring Boot 2 之间的所有区别的更多信息,请参阅 Spring Boot 的迁移指南和 Spring Boot 2 发行注记

1.1.1.1. Spring Boot 2 的新 Camel 组件

Spring Boot 2 支持 Camel 版本 2.23,因此支持一些不适用于 Spring Boot 1 的新的 camel 组件:

Spring Boot 2 的新 Camel 组件

  • as2-component
  • aws-iam-component
  • fhir-component
  • google-calendar-stream-component
  • google-mail-stream-component
  • google-sheets-component
  • google-sheets-stream-component
  • ipfs-component
  • kubernetes-hpa-component
  • kubernetes-job-component
  • micrometer-component
  • mybatis-bean-component
  • nsq-component
  • rxjava2
  • service-component
  • spring-cloud-consul
  • spring-cloud-zookeeper
  • testcontainers-spring
  • testcontainers
  • web3j-component

第 2 章 使用 Fuse boosters

Red Hat Fuse 提供以下 boosters,以帮助您开始使用 Fuse 应用程序并演示有用的组件:

2.1. 先决条件

要构建并运行 booster 演示,请安装以下先决条件:

  • 支持的 Java Developer Kit (JDK)版本。详情请查看 支持的配置页面
  • Apache Maven 3.3.x 或更高版本.请参阅 Maven Download 页面。

2.2. 生成您的 booster 项目

Fuse booster 项目存在,可帮助开发人员开始使用运行独立应用程序。此处提供的说明指导您生成其中一个增强项目,即 Circuit Breaker booster。此练习演示了 Spring Boot 上 Fuse 的有用组件。

Netflix/Hystrix 断路器使分布式应用能够处理对后端服务的网络连接和临时不可用的中断。断路器模式的基本理念是,自动检测到依赖服务的丢失,如果后端服务暂时不可用,可以编程替代行为。

Fuse 断路器提升器由两个相关服务组成:

  • 名称服务,将 名称 返回到 greet 的后端服务。
  • 一个 问候 服务,即调用 name 服务的 frontend 服务以获取名称,然后返回字符串 Hello, NAME

在此提升器演示中,Hystrix circuit breaker 在 问候器 服务和 名称服务 之间插入。如果 后端名称 服务不可用,则 问候 服务可能会回退到替代的行为并立即响应客户端,而不是在等待名称服务重启时被阻断。

先决条件

流程

  1. 进入 https://developers.redhat.com/launch
  2. 单击 START

    启动程序向导会提示您登录到您的红帽帐户。

  3. 单击 登录或注册 按钮,然后登录。
  4. Launcher 页面上,单击 Deploy an Example Application 按钮。
  5. Create Example Application 页面上,在 Create Example Application 字段中输入 name fuse-circuit-breaker
  6. Select an Example
  7. Example 对话框中,选择 Circuit Breaker 选项。此时会出现 选择运行时 下拉菜单。

    1. Select a Runtime 下拉菜单中选择 Fuse
    2. 从版本下拉菜单中,选择 7.5 (红帽 Fuse) (不要选择 2.21.2 (Community) 版本。
    3. Save
  8. Create Example Application 页面中,点 Download
  9. 当您看到您的应用程序 是 Ready 对话框时,点 Download.zip。您的浏览器下载生成的 booster 项目(打包为 ZIP 文件)。
  10. 使用存档实用程序将生成的项目提取到本地文件系统中的方便位置。

2.2.1. circuit Breaker booster

Netflix/Hystrix 断路器组件使分布式应用能够应对对后端服务的网络连接和临时不可用的中断。断路器模式的基本理念是,自动检测到依赖服务的丢失,如果后端服务暂时不可用,可以编程替代行为。

Fuse 断路器提升器由两个相关服务组成:

  • 名称服务,它将返回一个名称到 greet
  • 一个 问候服务,它调用 name 服务以获取名称,然后返回字符串 Hello, NAME

在演示中,Hystrix circuit breaker 在问候服务和名称服务之间插入。如果名称服务不可用,则问候服务可能会回退到替代的行为并立即响应客户端,而不是在等待名称服务重启时阻止或超时。

2.2.1.1. 构建并运行 Circuit Breaker booster

按照 Circuit Breaker mission 的 第 2.2 节 “生成您的 booster 项目” 步骤后,按照以下步骤构建并运行 Circuit breaker booster 项目:

  1. 打开 shell 提示符并使用 Maven 从命令行构建项目:

    cd PROJECT_DIR
    mvn clean package
    Copy to Clipboard Toggle word wrap
  2. 打开一个新的 shell 提示符并启动名称服务,如下所示:

    cd name-service
    mvn spring-boot:run -DskipTests -Dserver.port=8081
    Copy to Clipboard Toggle word wrap

    当 Spring Boot 启动时,您应该看到类似如下的输出:

    ...
    2017-12-08 15:44:24.223  INFO 22758 --- [           main] o.a.camel.spring.SpringCamelContext      : Total 1 routes, of which 1 are started
    2017-12-08 15:44:24.227  INFO 22758 --- [           main] o.a.camel.spring.SpringCamelContext      : Apache Camel 2.20.0 (CamelContext: camel-1) started in 0.776 seconds
    2017-12-08 15:44:24.234  INFO 22758 --- [           main] org.jboss.fuse.boosters.cb.Application   : Started Application in 4.137 seconds (JVM running for 4.744)
    Copy to Clipboard Toggle word wrap
  3. 打开一个新的 shell 提示符并启动问候服务,如下所示:

    cd greetings-service
    mvn spring-boot:run -DskipTests
    Copy to Clipboard Toggle word wrap

    当 Spring Boot 启动时,您应该看到类似如下的输出:

    ...
    2017-12-08 15:46:58.521  INFO 22887 --- [           main] o.a.c.c.s.CamelHttpTransportServlet      : Initialized CamelHttpTransportServlet[name=CamelServlet, contextPath=]
    2017-12-08 15:46:58.524  INFO 22887 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
    2017-12-08 15:46:58.536  INFO 22887 --- [           main] org.jboss.fuse.boosters.cb.Application   : Started Application in 6.263 seconds (JVM running for 6.819)
    Copy to Clipboard Toggle word wrap

    greetings 服务通过 URL 公开 REST 端点 http://localhost:8080/camel/greetings

  4. 进入 http://localhost:8080

    打开此页面时,它会调用 Greeting Service:

    此页面也提供到 Hystrix 仪表板的链接,它监控断路器的状态。

  5. 要演示 Camel Hystrix 提供的断路器功能,请在名称服务的 shell 提示符窗口中按 Ctrl+C 来终止后端名称服务。

    现在,名称服务不可用,断路器在 中启动,以防止在调用时问候服务挂起。

  6. 观察 Hystrix Monitor 仪表板和 Greeting Service 输出中的更改:

2.2.2. 外部化配置提升器

Externalized Configuration booster 提供了如何为 Apache Camel 路由外部配置的示例。对于 Spring Boot 独立部署,配置数据存储在 application.properties 文件中。

注意

对于 OpenShift 部署的 Fuse,配置数据存储在 ConfigMap 对象中。

2.2.2.1. 构建并运行 Externalized Configuration booster

按照 外部配置 任务的 第 2.2 节 “生成您的 booster 项目” 步骤后,按照以下步骤构建并运行外部配置提升为本地机器上的独立项目:

  1. 下载项目并在本地文件系统中提取存档。
  2. 构建项目:

    cd PROJECT_DIR
    mvn clean package
    Copy to Clipboard Toggle word wrap
  3. 运行该服务:

    mvn spring-boot:run
    Copy to Clipboard Toggle word wrap
  4. 打开 Web 浏览器,访问 http://localhost:8080。此页面每 5 秒调用一次 Greeting Service。Greetings Service 通过使用来自 target/classes/application.properties 文件中的 booster.nameToGreetvalue 来响应。

    Greeting Service 每 5 秒显示问候到"默认":

  5. 修改 booster.nameToGreet 值:

    1. 在编辑器中打开 target/classes/application.properties 文件。
    2. booster.nameToGreetvalue 的值从 默认值 改为另一个值,例如:

      booster.nameToGreetvalue=Thomas
      Copy to Clipboard Toggle word wrap
  6. 在终端窗口中,按 CTRL+C 来停止服务。
  7. 再次运行该服务:

    mvn spring-boot:run
    Copy to Clipboard Toggle word wrap
  8. 在 Web 浏览器中,返回到 http://localhost:8080 页面,在 Greeting Service 结果窗口中查看更改的值。

2.2.3. REST API booster

REST API 级别 0 任务演示了如何使用 REST 框架通过 HTTP 将业务运营映射到通过 HTTP 的远程过程调用端点。这个任务与用于 Matson Maturity Model 中的 Level 0 对应。

此提高器引入了使用 HTTP 协议与远程(由 Apache Camel 公开)服务交互的机制。通过使用此 Fuse 提升,您可以快速构建并灵活地设计 REST API。

使用这个 booster 来:

  • camel/greetings/{name} 端点上执行 HTTP GET 请求。此请求以 JSON 格式生成响应,有效负载为 Hello, $name! (其中 $name 替换为 HTTP GET 请求中的 URL 参数的值)。
  • 更改 URL {name} 参数的值,以查看响应中已更改的值。
  • 查看 REST API 的 Swagger 页面。
2.2.3.1. 构建并运行 REST API booster

在遵循 REST API 任务的 第 2.2 节 “生成您的 booster 项目” 步骤后,按照以下步骤构建并运行 REST API 提升为本地机器上的独立项目:

  1. 下载项目并在本地文件系统中提取存档。
  2. 构建项目:

    cd PROJECT_DIR
    mvn clean package
    Copy to Clipboard Toggle word wrap
  3. 运行该服务:

    mvn spring-boot:run
    Copy to Clipboard Toggle word wrap
  4. 打开 Web 浏览器 :http://localhost:8080
  5. 要执行 HTTP GET 请求示例,请单击 camel/greetings/{name} 按钮。

    此时会打开一个新的 Web 浏览器窗口,其中包含 localhost:8080/camel/greetings/Jacopo URL。URL {name} 参数的默认值为 Jacopo

    JSON 响应会出现在浏览器窗口中:

  6. 要更改 {name} 'parameter 的值,请更改 URL。例如,要将名称改为 netobserv,请使用此 URL: 'localhost:8080/camel/greetings/ Thomas

    更新的 JSON 响应会出现在浏览器窗口中:

  7. 要查看 REST API 的 Swagger 页面,请点 API Swagger 页面按钮。

    API swagger 页面在浏览器窗口中打开。

第 3 章 使用 Maven 构建

在 Fuse 中为 Spring Boot 开发应用程序的标准方法是使用 Apache Maven 构建工具,并将源代码构建为 Maven 项目。Fuse 提供 Maven 快速入门,以便您快速启动,许多 Fuse 构建工具都作为 Maven 插件提供。因此,强烈建议您使用 Maven 作为 Fuse 中的 Spring Boot 项目的构建工具。

3.1. 生成 Maven 项目

Fuse 提供基于 Maven archetypes 的快速入门选择,您可以使用它来为 Spring Boot 应用程序生成初始 Maven 项目。为了防止您记住各种 Maven 构架类型的位置信息和版本,Fuse 提供了工具来帮助您为独立的 Spring Boot 项目生成 Maven 项目。

3.1.1. developer.redhat.com/launch 的项目生成器

在 Fuse 中使用 Spring Boot 独立入门的最快速方法是导航到 developers.redhat.com/launch,并按照 Spring Boot 独立运行时的说明进行操作,以生成新的 Maven 项目。在遵循屏幕说明后,系统会提示您下载存档文件,其中包含一个完整的 Maven 项目,您可以在本地构建和运行。

3.1.2. Developer Studio 中的 Fuse 工具向导

或者,您可以下载并安装红帽 JBoss Developer Studio (包括 Fuse 工具)。使用 Fuse New Integration Project 向导,您可以生成新的 Spring Boot 独立项目,并继续开发基于 Eclipse 的 IDE。

3.2. 依赖于 Spring Boot 的 BOM

创建并构建第一个 Spring Boot 项目后,您很快会想添加更多组件。但是,您如何知道要添加到项目的 Maven 依赖项?最简单的(和推荐)方法是使用相关的 Bill of Materials (BOM)文件,该文件会自动为您定义所有版本依赖项。

3.2.1. Spring Boot 的 BOM 文件

Maven Bill of Materials (BOM) 文件的目的是提供一组可正常工作的 Maven 依赖项版本,从而防止您必须为每个 Maven 工件单独定义版本。

重要

确保您基于您使用的 Spring Boot 版本(Spring Boot 1 或 Spring Boot 2)使用正确的 Fuse BOM。

Spring Boot 的 Fuse BOM 提供以下优点:

  • 定义 Maven 依赖项的版本,以便在将依赖项添加到 POM 时不需要指定版本。
  • 定义一组对特定版本的 Fuse 经过全面测试并支持的策展依赖关系。
  • 简化 Fuse 的升级。
重要

红帽仅支持由 Fuse BOM 定义的一组依赖项。

3.2.1.1. 合并 BOM 文件

要将 BOM 文件合并到 Maven 项目中,请在项目的 pom.xml 文件中指定 dependencies Management 元素(或者,可能在父 POM 文件中),如下面的 Spring Boot 2 和 Spring Boot 1 示例所示:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project ...>
  ...
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <!-- configure the versions you want to use here -->
    <fuse.version>7.5.0.fuse-sb2-750029-redhat-00003</fuse.version>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.jboss.redhat-fuse</groupId>
        <artifactId>fuse-springboot-bom</artifactId>
        <version>${fuse.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
  ...
</project>
Copy to Clipboard Toggle word wrap


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project ...>
  ...
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <!-- configure the versions you want to use here -->
    <fuse.version>7.5.0.fuse-750029-redhat-00002</fuse.version>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.jboss.redhat-fuse</groupId>
        <artifactId>fuse-springboot-bom</artifactId>
        <version>${fuse.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
  ...
</project>
Copy to Clipboard Toggle word wrap

使用依赖项管理机制指定 BOM 后,可以在不指定工件版本 的情况下 向 POM 添加 Maven 依赖项。例如,要为 camel-hystrix 组件添加依赖项,您可以在 POM 中的 dependencies 元素中添加以下 XML 片段:

<dependency>
  <groupId>org.apache.camel</groupId>
  <artifactId>camel-hystrix-starter</artifactId>
</dependency>
Copy to Clipboard Toggle word wrap

请注意,Camel 工件 ID 如何通过 -starter 后缀,将 Camel Hystrix 组件指定为 camel-hystrix-starter,而不是 camel-hystrix。Camel 初学者组件以针对 Spring Boot 环境进行了优化的方式进行打包。

3.2.2. Spring Boot Maven 插件

Spring Boot Maven 插件由 Spring Boot 提供,它是一个用于构建和运行 Spring Boot 项目的开发人员实用程序:

  • 通过在项目目录中输入 mvn package,为您的 Spring Boot 应用程序 构建 可执行文件 Jar 软件包。构建的输出放置在 Maven 项目的 target/ 子目录中。
  • 为方便起见,您可以使用命令 mvn spring-boot:start 运行新构建的应用程序。

要将 Spring Boot Maven 插件合并到项目 POM 文件中,请将插件配置添加到 pom.xml 文件的 project/build/plugins 部分,如下例所示:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project ...>
  ...
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <!-- configure the versions you want to use here -->
    <fuse.version>7.5.0.fuse-750029-redhat-00002</fuse.version>

  </properties>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.jboss.redhat-fuse</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>${fuse.version}</version>
        <executions>
          <execution>
            <goals>
              <goal>repackage</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  ...
</project>
Copy to Clipboard Toggle word wrap

第 4 章 Spring Boot 中的 Apache Camel

4.1. Camel Spring Boot 简介

Camel Spring Boot 组件为 Apache Camel 提供自动配置。Camel 上下文自动配置会在 Spring 上下文中自动探测 Camel 路由,并将生成者模板、消费者模板以及类型转换器注册为 Bean。

每个 Camel Spring Boot 应用程序都应该使用带有产品化版本 的依赖关系管理,请参阅 Quickstart pom。之后标记的版本可以被省略,无法覆盖 BOM 中的版本。

<dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>org.jboss.redhat-fuse</groupId>
			<artifactId>fuse-springboot-bom</artifactId>
			<version>${fuse.version}</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
	</dependencies>
</dependencyManagement>
Copy to Clipboard Toggle word wrap
注意

camel-spring-boot jar 附带 spring.factories 文件,该文件允许您将依赖项添加到您的类路径中,因此 Spring Boot 将自动配置 Camel。

4.2. Camel Spring Boot Starter 简介

Apache Camel 包含一个 Spring Boot starter 模块,允许您使用启动程序开发 Spring Boot 应用程序。

注意

如需了解更多详细信息,请参阅链接: Apache Camel Spring-Boot 示例

要使用初学者,请在 Spring Boot pom.xml 文件中添加以下代码片段:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-spring-boot-starter</artifactId>
</dependency>
Copy to Clipboard Toggle word wrap

初学者允许您使用 Camel 路由添加类,如以下代码片段所示。将这些路由添加到类路径中后,路由会自动启动。

package com.example;

import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;

@Component
public class MyRoute extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        from("timer:foo").to("log:bar");
    }
}
Copy to Clipboard Toggle word wrap

您可以在 application.propertiesapplication.yml 文件中自定义 Camel 应用程序。

在配置任何 Camel 入门组件时,Camel Spring Boot 现在支持根据配置文件(application.properties 或 yaml 文件中)中的 id 名称引用 bean。在 src/main/resources/application.properties (或 yaml)文件中,您现在可以通过引用 Bean ID 名称在 Camel 上轻松配置选项。例如,xslt 组件可以使用 bean ID 引用自定义 bean,如下所示:

请参考 id myExtensionFactory 的自定义 bean,如下所示:

camel.component.xslt.saxon-extension-functions=myExtensionFactory
Copy to Clipboard Toggle word wrap

然后您可以使用 Spring Boot @Bean 注释来创建,如下所示:

@Bean(name = "myExtensionFactory")
public ExtensionFunctionDefinition myExtensionFactory() {
    }
Copy to Clipboard Toggle word wrap

或者,如果 camel-jackson data-format 中的 Jackson ObjectMapper:

camel.dataformat.json-jackson.object-mapper=myJacksonMapper
Copy to Clipboard Toggle word wrap

4.3. 自动配置的 Camel 上下文

Camel 自动配置提供 CamelContext 实例,并创建 SpringCamelContext。它还初始化并执行该上下文的关机。此 Camel 上下文在 camelContext bean 名称下的 Spring 应用程序上下文中注册,您可以像其他 Spring bean 一样访问它。

例如,您可以访问 camelContext,如下所示:

@Configuration
public class MyAppConfig {

  @Autowired
  CamelContext camelContext;

  @Bean
  MyService myService() {
    return new DefaultMyService(camelContext);
  }

}
Copy to Clipboard Toggle word wrap

4.4. 自动探测 Camel 路由

Camel 自动配置从 Spring 上下文收集所有 RouteBuilder 实例,并将它们自动注入到 CamelContext 中。它简化了使用 Spring Boot 初学者创建新的 Camel 路由的过程。您可以通过在 classpath 中添加 @Component annotated 类来创建路由。

@Component
public class MyRouter extends RouteBuilder {

  @Override
  public void configure() throws Exception {
    from("jms:invoices").to("file:/invoices");
  }

}
Copy to Clipboard Toggle word wrap

要在 @Configuration 类中创建新的路由 RouteBuilder bean,请参阅以下:

@Configuration
public class MyRouterConfiguration {

  @Bean
  RoutesBuilder myRouter() {
    return new RouteBuilder() {

      @Override
      public void configure() throws Exception {
        from("jms:invoices").to("file:/invoices");
      }

    };
  }

}
Copy to Clipboard Toggle word wrap

4.5. Camel 属性

Spring Boot 自动配置会自动连接到 Spring Boot 外部配置,如属性占位符、OS 环境变量或带有 Camel 属性的系统属性。

这些属性在 application.properties 文件中定义:

route.from = jms:invoices
Copy to Clipboard Toggle word wrap

使用 作为系统属性

java -Droute.to=jms:processed.invoices -jar mySpringApp.jar
Copy to Clipboard Toggle word wrap

在 Camel 路由中使用 作为占位符:

@Component
public class MyRouter extends RouteBuilder {

  @Override
  public void configure() throws Exception {
    from("{{route.from}}").to("{{route.to}}");
  }

}
Copy to Clipboard Toggle word wrap

4.6. 自定义 Camel 上下文配置

要在 Camel 自动配置创建的 CamelContext bean 上执行操作,您需要在 Spring 上下文中注册 CamelContextConfiguration 实例,如下所示:

@Configuration
public class MyAppConfig {

  ...

  @Bean
  CamelContextConfiguration contextConfiguration() {
    return new CamelContextConfiguration() {
      @Override
      void beforeApplicationStart(CamelContext context) {
        // your custom configuration goes here
      }
    };
  }

}
Copy to Clipboard Toggle word wrap
注意

在 Spring 上下文启动前,将调用方法 CamelContextConfigurationbeforeApplicationStart (CamelContext),因此传递给此回调的 CamelContext 实例完全自动配置。您可以将许多 CamelContextConfiguration 实例添加到 Spring 上下文中,并且所有实例都将被执行。

4.7. 禁用 JMX

要禁用自动配置的 CamelContext 的 JMX,请使用 camel.springboot.jmxEnabled 属性,因为默认启用 JMX。

例如,您可以在 application.properties 文件中添加以下属性:

camel.springboot.jmxEnabled = false
Copy to Clipboard Toggle word wrap

4.8. 自动配置的消费者和制作者模板

Camel 自动配置提供预配置的 ConsumerTemplateProducerTemplate 实例。您可以将它们注入到 Spring 管理的 Bean 中:

@Component
public class InvoiceProcessor {

  @Autowired
  private ProducerTemplate producerTemplate;

  @Autowired
  private ConsumerTemplate consumerTemplate;
  public void processNextInvoice() {
    Invoice invoice = consumerTemplate.receiveBody("jms:invoices", Invoice.class);
    ...
    producerTemplate.sendBody("netty-http:http://invoicing.com/received/" + invoice.id());
  }

}
Copy to Clipboard Toggle word wrap

默认情况下,消费者模板和制作者模板随端点缓存大小设置为 1000。您可以使用以下 Spring 属性更改这些值:

camel.springboot.consumerTemplateCacheSize = 100
camel.springboot.producerTemplateCacheSize = 200
Copy to Clipboard Toggle word wrap

4.9. 自动配置的 TypeConverter

Camel 自动配置在 Spring 上下文中注册一个名为 typeConverterTypeConverter 实例。

@Component
public class InvoiceProcessor {

  @Autowired
  private TypeConverter typeConverter;

  public long parseInvoiceValue(Invoice invoice) {
    String invoiceValue = invoice.grossValue();
    return typeConverter.convertTo(Long.class, invoiceValue);
  }

}
Copy to Clipboard Toggle word wrap

4.10. Spring 类型转换 API 网桥

Spring 由 类型转换 API 组成。Spring API 与 Camel 类型转换器 API 类似。由于两个 API Camel Spring Boot 之间的相似性会自动注册桥接转换器(SpringTypeConverter),它委托给 Spring 转换 API。这意味着开箱即用的 Camel 将对待与 Camel 类似的 Spring Converters。

这可让您使用 Camel TypeConverter API 访问 Camel 和 Spring 转换器,如下所示:

@Component
public class InvoiceProcessor {

  @Autowired
  private TypeConverter typeConverter;

  public UUID parseInvoiceId(Invoice invoice) {
    // Using Spring's StringToUUIDConverter
    UUID id = invoice.typeConverter.convertTo(UUID.class, invoice.getId());
  }

}
Copy to Clipboard Toggle word wrap

这里,Spring Boot 将转换委托给应用程序上下文中提供的 Spring ConversionService 实例。如果没有 ConversionService 实例,Camel Spring Boot 自动配置会创建一个 ConversionService 实例。

4.11. 禁用类型转换功能

要禁用 Camel Spring Boot 的注册类型转换功能,如 TypeConverter 实例或 Spring 网桥,请将 camel.springboot.typeConversion 属性设置为 false,如下所示:

camel.springboot.typeConversion = false
Copy to Clipboard Toggle word wrap

4.12. 添加 XML 路由

默认情况下,您可以将 Camel XML 路由放在 camel 目录下的 classpath 中,camel-spring-boot 将自动检测并包含。从 Camel 版本 2.17 开始,您可以使用配置选项配置目录名称或禁用此功能,如下所示:

// turn off
camel.springboot.xmlRoutes = false
// scan in the com/foo/routes classpath
camel.springboot.xmlRoutes = classpath:com/foo/routes/*.xml
Copy to Clipboard Toggle word wrap
注意

XML 文件应该是 Camel XML 路由,而不是 CamelContext,例如:

   <routes xmlns="http://camel.apache.org/schema/spring">
        <route id="test">
            <from uri="timer://trigger"/>
            <transform>
                <simple>ref:myBean</simple>
            </transform>
            <to uri="log:out"/>
        </route>
    </routes>
Copy to Clipboard Toggle word wrap

使用带有 <camelContext> 的 Spring XML 文件时,您可以在 Spring XML 文件和 application.properties 文件中配置 Camel。例如,要在 Camel 上设置名称并打开流缓存,请添加:

camel.springboot.name = MyCamel
camel.springboot.stream-caching-enabled=true
Copy to Clipboard Toggle word wrap

4.13. 添加 XML Rest-DSL

默认情况下,您可以将 Camel Rest-DSL XML 路由放在 camel-rest 目录下的类路径中,camel-spring-boot 将自动检测并包含。您可以使用配置选项配置目录名称或禁用此功能,如下所示:

// turn off
camel.springboot.xmlRests = false
// scan in the com/foo/routes classpath
camel.springboot.xmlRests = classpath:com/foo/rests/*.xml
Copy to Clipboard Toggle word wrap
注意

Rest-DSL XML 文件应该是 Camel XML rests,而不是 CamelContext,例如:

   <rests xmlns="http://camel.apache.org/schema/spring">
      <rest>
         <post uri="/persons">
            <to uri="direct:postPersons"/>
         </post>
         <get uri="/persons">
            <to uri="direct:getPersons"/>
         </get>
         <get uri="/persons/{personId}">
             <to uri="direct:getPersionId"/>
         </get>
         <put uri="/persons/{personId}">
             <to uri="direct:putPersionId"/>
         </put>
         <delete uri="/persons/{personId}">
             <to uri="direct:deletePersionId"/>
         </delete>
      </rest>
    </rests>
Copy to Clipboard Toggle word wrap

4.14. 使用 Camel Spring Boot 测试

如果在 Spring Boot 上运行的 Camel 上,Spring Boot 会自动嵌入 Camel 及其所有路由,这些路由使用 @Component 标注。当使用 Spring 引导测试时,您可以使用 @SpringBootTest 而不是 @ContextConfiguration 来指定要使用的配置类。

当您在不同的 RouteBuilder 类中有多个 Camel 路由时,Camel Spring Boot 将包括所有这些路由。因此,当您希望只从一个 RouteBuilder 类测试路由时,您可以使用以下模式包含或排除要启用的 RouteBuilders:

  • java-routes-include-pattern: 用于包括与模式匹配的 RouteBuilder 类。
  • java-routes-exclude-pattern: 用于排除与模式匹配的 RouteBuilder 类。exclude 优先于 include。

您可以在单元测试类中指定这些模式,作为 @SpringBootTest 注释的属性,如下所示:

@RunWith(CamelSpringBootRunner.class)
@SpringBootTest(classes = {MyApplication.class);
   properties = {"camel.springboot.java-routes-include-pattern=**/Foo*"})
public class FooTest {
Copy to Clipboard Toggle word wrap

FooTest 类中,include 模式是 **/Foo*,它代表 Ant 样式模式。在这里,模式以双星号开头,它与任何前导软件包名称匹配。/foo* 表示类名称必须以 Foo 开头,例如 FooRoute。您可以使用以下 maven 命令运行测试:

mvn test -Dtest=FooTest
Copy to Clipboard Toggle word wrap

4.15. 另请参阅

4.16.1. 使用外部消息传递代理。

Fuse 使用外部消息传递代理。有关支持的代理、客户端和 Camel 组件组合的更多信息,请参阅 支持的配置

Camel 组件必须连接到 JMS connection-factory。以下示例演示了如何将 camel-amqp 组件连接到 JMS connection-factory。

import org.apache.activemq.jms.pool.PooledConnectionFactory;
import org.apache.camel.component.amqp.AMQPComponent;
import org.apache.qpid.jms.JmsConnectionFactory;
...

AMQPComponent amqpComponent(AMQPConfiguration config) {
       JmsConnectionFactory qpid = new JmsConnectionFactory(config.getUsername(), config.getPassword(), "amqp://"+ config.getHost() + ":" + config.getPort());
       qpid.setTopicPrefix("topic://");

       PooledConnectionFactory factory = new PooledConnectionFactory();
       factory.setConnectionFactory(qpid);

AMQPComponent amqpcomp = new AMQPComponent(factory);
Copy to Clipboard Toggle word wrap

附录 A. 准备使用 Maven

A.1. 概述

本节概述了如何准备 Maven 以构建红帽 Fuse 项目,并介绍了用于定位 Maven 工件的 Maven 协调的概念。

A.2. 先决条件

要使用 Maven 构建项目,您必须满足以下先决条件:

  • Maven 安装 criu-wagonMaven 是 Apache 的免费开源构建工具。您可以从 Maven 下载页面 下载最新版本
  • 网络连接 mvapich - iwlwhilst 执行构建,Maven 会动态搜索外部存储库,并即时下载所需的工件。默认情况下,Maven 会查找通过互联网访问的存储库。您可以更改此行为,以便 Maven 首选搜索位于本地网络上的存储库。

    注意

    Maven 可以在离线模式下运行。在离线模式中,Maven 仅在其本地存储库中查找工件。

A.3. 添加 Red Hat Maven 存储库

要访问 Red Hat Maven 存储库中的工件,您需要将它们添加到 Maven 的 settings.xml 文件中。Maven 在用户主目录的 .m2 目录中查找您的 settings.xml 文件。如果没有用户指定的 settings.xml 文件,Maven 将使用 M2_HOME/conf/ settings.xml 中的系统级 settings.xml 文件。

要将红帽存储库添加到 Maven 存储库列表中,您可以创建一个新的 .m2/settings.xml 文件或修改系统级设置。在 settings.xml 文件中,为红帽 软件仓库 添加软件仓库元素,如 将 Red Hat Fuse 存储库添加到 Maven 所示。

将 Red Hat Fuse 存储库添加到 Maven

<?xml version="1.0"?>
<settings>

  <profiles>
    <profile>
      <id>extra-repos</id>
      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>
      <repositories>
       <repository>
            <id>redhat-ga-repository</id>
            <url>https://maven.repository.redhat.com/ga</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>redhat-ea-repository</id>
            <url>https://maven.repository.redhat.com/earlyaccess/all</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
          <id>jboss-public</id>
          <name>JBoss Public Repository Group</name>
          <url>https://repository.jboss.org/nexus/content/groups/public/</url>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
            <id>redhat-ga-repository</id>
            <url>https://maven.repository.redhat.com/ga</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>redhat-ea-repository</id>
            <url>https://maven.repository.redhat.com/earlyaccess/all</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
          <id>jboss-public</id>
          <name>JBoss Public Repository Group</name>
          <url>https://repository.jboss.org/nexus/content/groups/public</url>
        </pluginRepository>
      </pluginRepositories>
    </profile>
  </profiles>

  <activeProfiles>
    <activeProfile>extra-repos</activeProfile>
  </activeProfiles>

</settings>
Copy to Clipboard Toggle word wrap

A.4. 工件

Maven 构建系统中的基本构建块是一个 工件。在执行 Maven 构建后,工件的输出通常是一个存档,如 JAR 或 WAR。

A.5. Maven 协调

Maven 功能的一个关键方面是能够找到工件和管理它们之间的依赖关系。Maven 使用 Maven 协调 的系统定义工件的位置,它唯一定义特定工件的位置。一个基本的协调元组具有表单 {groupId,artifactId,version}。有时,Maven 会增加基本协调集与额外的协调、打包和 分类器。可以使用基本协调或额外的 打包 协调编写元组,或者添加 打包和 分类器 协调,如下所示:

groupdId:artifactId:version
groupdId:artifactId:packaging:version
groupdId:artifactId:packaging:classifier:version
Copy to Clipboard Toggle word wrap

每个协调都可以解释,如下所示:

groupdId
定义工件名称的范围。您通常使用所有或部分软件包名称作为组 ID iwl-8:0:1:: 例如 org.fusesource.example
artifactId
定义工件名称(相对于组 ID)。
version
指定工件的版本。版本号最多可有四个部分: n.n.n.n,其中版本号的最后一部分可以包含非数字字符(例如 1.0-SNAPSHOT 的最后一部分是字母数字,0-SNAPSHOT)。
打包
定义构建项目时生成的打包实体。对于 OSGi 项目,打包是 捆绑包。默认值为 jar
classifier
可让您区分从同一 POM 构建但具有不同内容的工件。

组 ID、工件 ID、打包和版本由工件的 POM 文件中的对应元素定义。例如:

<project ... >
  ...
  <groupId>org.fusesource.example</groupId>
  <artifactId>bundle-demo</artifactId>
  <packaging>bundle</packaging>
  <version>1.0-SNAPSHOT</version>
  ...
</project>
Copy to Clipboard Toggle word wrap

例如,要定义对上述工件的依赖项,您可以在 POM 中添加以下 dependencies 元素:

<project ... >
  ...
  <dependencies>
    <dependency>
      <groupId>org.fusesource.example</groupId>
      <artifactId>bundle-demo</artifactId>
      <version>1.0-SNAPSHOT</version>
    </dependency>
  </dependencies>
  ...
</project>
Copy to Clipboard Toggle word wrap
注意

不需要在 前面的依赖项中指定 bundle 软件包类型,因为捆绑包只是特定类型的 JAR 文件,jar 是默认的 Maven 软件包类型。但是,如果您需要在依赖项中明确指定打包类型,您可以使用 type 元素。

附录 B. Spring Boot Maven 插件

B.1. Spring Boot Maven 插件概述

本附录描述了 Spring Boot Maven 插件。它在 Maven 中提供 Spring Boot 支持,并允许您打包可执行文件 jar 或 war 归档并运行应用程序 原位

B.2. 目标

Spring Boot 插件包括以下目标:

  1. spring-boot:run 运行 Spring Boot 应用程序。
  2. spring-boot:repackage 将您的 .jar.war 文件重新打包为可执行文件。
  3. spring-boot:startspring-boot:stop 均用于管理 Spring Boot 应用程序的生命周期。
  4. spring-boot:build-info 生成可由 Actuator 使用的构建信息。

B.3. 使用方法

您可以在以下位置找到有关如何使用 Spring Boot 插件的通用说明 :https://docs.spring.io/spring-boot/docs/current/maven-plugin/reference/htmlsingle/#using。以下示例演示了为 Spring Boot 使用 spring-boot-maven-plugin

注意

有关 Spring Boot Maven 插件的更多信息,请参阅 https://docs.spring.io/spring-boot/docs/current/maven-plugin/reference/htmlsingle/

B.3.1. Spring Boot 2 的 Spring Boot Maven 插件

<project>
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.redhat.fuse</groupId>
  <artifactId>spring-boot-camel</artifactId>
  <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

        <!-- configure the Fuse version you want to use here -->
        <fuse.bom.version>7.5.0.fuse-sb2-750029-redhat-00003</fuse.bom.version>

        <!-- maven plugin versions -->
        <maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
        <maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
    </properties>


    <build>
        <defaultGoal>spring-boot:run</defaultGoal>

        <plugins>
            <plugin>
                <groupId>org.jboss.redhat-fuse</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${fuse.bom.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>redhat-ga-repository</id>
            <url>https://maven.repository.redhat.com/ga</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>redhat-ea-repository</id>
            <url>https://maven.repository.redhat.com/earlyaccess/all</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>redhat-ga-repository</id>
            <url>https://maven.repository.redhat.com/ga</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>redhat-ea-repository</id>
            <url>https://maven.repository.redhat.com/earlyaccess/all</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
</project>
Copy to Clipboard Toggle word wrap

B.3.2. Spring Boot 1 的 Spring Boot Maven 插件

<project>
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.redhat.fuse</groupId>
  <artifactId>spring-boot-camel</artifactId>
  <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

        <!-- configure the Fuse version you want to use here -->
        <fuse.bom.version>7.5.0.fuse-750029-redhat-00002</fuse.bom.version>

        <!-- maven plugin versions -->
        <maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
        <maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
    </properties>


    <build>
        <defaultGoal>spring-boot:run</defaultGoal>

        <plugins>
            <plugin>
                <groupId>org.jboss.redhat-fuse</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${fuse.bom.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>redhat-ga-repository</id>
            <url>https://maven.repository.redhat.com/ga</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>redhat-ea-repository</id>
            <url>https://maven.repository.redhat.com/earlyaccess/all</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>redhat-ga-repository</id>
            <url>https://maven.repository.redhat.com/ga</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>redhat-ea-repository</id>
            <url>https://maven.repository.redhat.com/earlyaccess/all</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
</project>
Copy to Clipboard Toggle word wrap

法律通告

Copyright © 2023 Red Hat, Inc.
The text of and illustrations in this document are licensed by Red Hat under a Creative Commons Attribution–Share Alike 3.0 Unported license ("CC-BY-SA"). An explanation of CC-BY-SA is available at http://creativecommons.org/licenses/by-sa/3.0/. In accordance with CC-BY-SA, if you distribute this document or an adaptation of it, you must provide the URL for the original version.
Red Hat, as the licensor of this document, waives the right to enforce, and agrees not to assert, Section 4d of CC-BY-SA to the fullest extent permitted by applicable law.
Red Hat, Red Hat Enterprise Linux, the Shadowman logo, the Red Hat logo, JBoss, OpenShift, Fedora, the Infinity logo, and RHCE are trademarks of Red Hat, Inc., registered in the United States and other countries.
Linux® is the registered trademark of Linus Torvalds in the United States and other countries.
Java® is a registered trademark of Oracle and/or its affiliates.
XFS® is a trademark of Silicon Graphics International Corp. or its subsidiaries in the United States and/or other countries.
MySQL® is a registered trademark of MySQL AB in the United States, the European Union and other countries.
Node.js® is an official trademark of Joyent. Red Hat is not formally related to or endorsed by the official Joyent Node.js open source or commercial project.
The OpenStack® Word Mark and OpenStack logo are either registered trademarks/service marks or trademarks/service marks of the OpenStack Foundation, in the United States and other countries and are used with the OpenStack Foundation's permission. We are not affiliated with, endorsed or sponsored by the OpenStack Foundation, or the OpenStack community.
All other trademarks are the property of their respective owners.
返回顶部
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2025 Red Hat