Red Hat build of Apache Camel for Spring Boot のスタートガイド


Red Hat build of Apache Camel 4.10

概要

このガイドでは、Red Hat build of Apache Camel を紹介し、Red Hat build of Apache Camel を使用してアプリケーションを作成およびデプロイするさまざまな方法を説明します。

はじめに

多様性を受け入れるオープンソースの強化

Red Hat では、コード、ドキュメント、Web プロパティーにおける配慮に欠ける用語の置き換えに取り組んでいます。まずは、マスター (master)、スレーブ (slave)、ブラックリスト (blacklist)、ホワイトリスト (whitelist) の 4 つの用語の置き換えから始めます。この取り組みは膨大な作業を要するため、用語の置き換えは、今後の複数のリリースにわたって段階的に実施されます。詳細は、Red Hat CTO である Chris Wright のメッセージ をご覧ください。

第1章 統合されたオープンソース機能にアクセス

Red Hat build of Apache Camel は、さまざまな環境で認定およびサポートされており、オープンソースインテグレーションプロジェクトにおける最適なの部分を強力なエンタープライズ対応ツールキットに組み合わせて、現代のビジネスにおけるクラウドネイティブインテグレーションを簡素化および加速するように設計されています。

このようなインテグレーションは次のとおりです。

  • Apache Camel 統合フレームワーク: エンタープライズ統合パターンを実装し、数百の構築済みコンポーネントとコネクターを提供します。
  • Kaoto ビジュアルデザイナー: Apache Camel 用。
  • HawtIO モジュラー Web コンソール: 統合のトラブルシューティングとリモート管理用。
  • Apache CXF: Simple Object Access Protocol (SOAP) Web サービスを開発および使用するため。
  • Camel CLI: 反復的な統合プロトタイピング用。
  • VS Code 開発ツール: コードのサポートおよびデバッグ用。
  • ライセンスライブラリーを必要とする 追加の Camel コンポーネント
  • Camel ゴールデンパステンプレート: Backstage 用。
  • 監視とトレース: Prometheus および OpenTelemetry 経由。
  • Narayana: トランザクションマネージャー。
  • Quarkus および Spring Boot: ランタイム。
  • Quarkus プラットフォームのメンバー: 同時セキュリティー更新あり。

第2章 ツールについて

2.1. Languages

Red Hat build of Apache Camel for Spring Boot では、以下の言語を使用して Camel ルートを定義できます。

  • Java DSL
  • YAML
  • XML IO

2.2. HawtIO 診断コンソール

HawtIO 診断コンソールは、React や PatternFly などの最新の Web テクノロジーを使用して構築された Red Hat build of Apache Camel 用のプラグ可能な Web 診断コンソールです。HawtIO は、有効になっているプラグインに応じて、デプロイされた 1 つ以上の HawtIO 対応コンテナーの詳細を確認および管理するための中央インターフェイスを提供します。HawtIO およびシステムリソースの監視、更新の実行、およびサービスの起動と停止を行うことができます。

詳細は、HawtIO 診断コンソール のドキュメントを参照してください。

2.3. Kaoto

Kaoto (Kamel Orchestration Tool) は、Apache Camel をベースにしたローコードおよびノーコードの統合デザイナーであり、統合の作成と編集が可能です。Kaoto は拡張可能で柔軟性があり、さまざまなユースケースに適応できます。

詳細は、Kaoto ドキュメントの Camel ルートの作成 セクションを参照してください。

2.4. Camel CLI

Camel CLI は、Camel ルートの作成と実行に使用できる JBang ベースの Camel アプリケーションです。

詳細は、Red Hat build of Apache Camel for Spring Boot ツールガイド ドキュメントの Camel ルートの作成と実行 セクションを参照してください。

2.5. IDE プラグイン

Red Hat build of Apache Camel for Spring Boot には、言語サポート、コード/設定の補完、プロジェクト作成ウィザードなどを提供する、ほとんどの一般的な開発 IDE 用のプラグインが含まれています。プラグインは、それぞれの IDE マーケットプレイスで利用できます。

  • VS Code:

    • Camel エクステンションパック:

      • Language Support for Apache Camel
      • Apache Camel のデバッグアダプター
      • Kaoto
      • Extension Pack for Java
      • Spring Boot Extension Pack
      • OpenShift Toolkit
      • Kubernetes
      • YAML
      • XML
      • Tools for MicroProfile
      • Quarkus
  • Eclipse:

    Eclipse プラグイン (現在はサポートされていません)

  • Jetbrains:

    IntelliJ プラグイン (現在はサポートされていません)

プラグインのドキュメントを参照して、お好みの IDE プロジェクトの作成方法を見つけてください。

2.6. Camel コンテンツアシスト

以下のプラグインは、Camel ルートおよび application.properties の編集時にコンテンツアシストをサポートします。

  • Eclipse:

    • Jboss ツール:

      • Eclipse Desktop Language Support for Camel
  • JetBrains:

    Apache Camel IDEA プラグイン (常に最新の状態であるとは限りません)

  • VS Code:

    • Camel エクステンションパック:

      • VS Code Language support for Camel
      • Java、YAML、または XML で記述された Camel 統合をローカルでデバッグするための Apache Camel 用デバッグアダプター
      • YAML
      • XML
  • その他:

    If you are using any other IDE that supports Language Server Protocol you can install and configure Camel Language Server manually
    Copy to Clipboard Toggle word wrap
    ヒント
    For more information about Tooling in Red Hat build of Apache Camel, see link:https://docs.redhat.com/en/documentation/red_hat_build_of_apache_camel/4.10/html-single/tooling_guide_for_red_hat_build_of_apache_camel/index[Tooling Guide].
    
    For more information about scope of development support, see link:https://access.redhat.com/support/offerings/developer/soc[Development Support Scope of Coverage] in the Red Hat Support Portal (requires login).
    Copy to Clipboard Toggle word wrap

第3章 Red Hat build of Apache Camel for Spring Boot のスタートガイド

このガイドでは、Red Hat build of Apache Camel for Spring Boot を紹介し、Red Hat build of Apache Camel for Spring Boot を使用してアプリケーションの構築を開始する方法を示します。

3.1. Red Hat build of Apache Camel for Spring Boot のスターター

Spring Boot の Camel サポートは、Camel の自動設定と多くの Camel コンポーネント のスターターを提供します。Camel コンテキストの独自の自動設定は、Spring コンテキストで使用可能な Camel ルートを自動検出し、主要な Camel ユーティリティー (producer テンプレート、コンシューマーテンプレート、型コンバーターなど) を Bean として登録します。

注記

Maven アーキタイプを使用して Camel for Spring Boot アプリケーションを生成する方法は、Maven を使用した Spring Boot アプリケーション用の Camel 生成 を参照してください。

まず、Camel Spring Boot BOM を Maven pom.xml ファイルに追加する必要があります。

<dependencyManagement>

    <dependencies>
        <!-- Camel BOM -->
        <dependency>
            <groupId>com.redhat.camel.springboot.platform</groupId>
            <artifactId>camel-spring-boot-bom</artifactId>
            <version>4.10.7.redhat-00013</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <!-- ... other BOMs or dependencies ... -->
    </dependencies>

</dependencyManagement>
Copy to Clipboard Toggle word wrap

camel-spring-boot-bom は、Camel Spring Boot スターター JAR のリストを含む基本的な BOM です。

次に、Camel Spring Boot スターター を追加して Camel Context を起動します。

    <dependencies>
        <!-- Camel Starter -->
        <dependency>
            <groupId>org.apache.camel.springboot</groupId>
            <artifactId>camel-spring-boot-starter</artifactId>
        </dependency>
        <!-- ... other dependencies ... -->
    </dependencies>
Copy to Clipboard Toggle word wrap

Spring Boot アプリケーションに必要な コンポーネントスターター も追加する必要があります。次の例は、自動設定スターターMQTT5 コンポーネント に追加する方法を示しています。

    <dependencies>
        <!-- ... other dependencies ... -->
        <dependency>
            <groupId>org.apache.camel.springboot</groupId>
            <artifactId>camel-paho-mqtt5</artifactId>
        </dependency>
    </dependencies>
Copy to Clipboard Toggle word wrap

3.1.1. Spring Boot 設定のサポート

スターター には、標準の application.properties または application.yml ファイルで設定できる設定パラメーターがリストされています。これらのパラメーターの形式は camel.component.[component-name].[parameter] です。たとえば、MQTT5 ブローカーの URL を設定するには、次のように設定できます。

camel.component.paho-mqtt5.broker-url=tcp://localhost:61616
Copy to Clipboard Toggle word wrap

3.1.2. Camel ルートの追加

Camel ルート は Spring アプリケーションコンテキストで検出されます。たとえば、org.springframework.stereotype.Component でアノテーションが付けられたルートがロードされ、Camel コンテキストに追加されて実行されます。

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

@Component
public class MyRoute extends RouteBuilder {

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

}
Copy to Clipboard Toggle word wrap

3.1.3. ドメイン固有言語の使用

Apache Camel は、以下に示すさまざまなドメイン固有言語 (DSL) でエンタープライズ統合パターンまたはルートを作成するために、Java ドメイン固有言語 (DSL) を使用します。

  • Java DSL: Fluent Builder スタイルを使用する Java ベースの DSL。
  • XML DSL: Camel XML ファイル限定の XML ベースの DSL。
  • Yaml DSL: YAML 形式を使用してルートを作成するための DSL。
3.1.3.1. DSL の利点

汎用言語ではなく DSL を使用する利点は次のとおりです。

  • 学習しやすく、作業も簡単になります。メインロジックがどこで始まり、どこで終わるか明確です。
  • コードの安全性が向上します。Apache Camel の DSL には、すべてのステップを結合する強固なビルディングブロックがあります。
  • エラーはドメイン固有です。障害が発生した場合、エラーの説明がより明確でわかりやすくなります。コードがシンプルになることで、エラーが発生しにくくなります。
  • DSL はプラットフォームに依存しないように設計されています。コードが変更された場合、その影響は下位層に委譲されます。
3.1.3.2. 各種 DSL の比較

次のセクションでは、各種 DSL の違いと、各 DSL を使用するシナリオを説明します。

Expand
 Java DSLXML DSLYAML DSL

開発者ツール

  • Java をサポートするあらゆる IDE を使用できます。
  • Red Hat は、Apache Camel in VS Code 用のエクステンションパックを提供しています。このパックには、VS Code で Red Hat build of Apache Camel を操作するために必要なエクステンションがすべて含まれています。これには、Camel K Java スタンドアロンの言語サポート、Camel URI 補完と診断のサポート、ソースエディターからの Camel ルートの実行とデバッグが含まれます。
  • 言語サポートと基本的な Camel テキストルートのデバッグ。
  • コード支援とルートデバッガーを提供します。
  • XML をサポートするあらゆる IDE を使用できます。
  • Red Hat は、Apache Camel in VS Code 用のエクステンションパックを提供しています。このパックには、VS Code で Red Hat build of Apache Camel を操作するために必要なエクステンションがすべて含まれています。これには、Camel K Java スタンドアロンの言語サポート、Camel URI 補完と診断のサポート、ソースエディターからの Camel ルートの実行とデバッグが含まれます。
  • 言語サポートと基本的な Camel テキストルートのデバッグ
  • コード支援とルートデバッガーを提供します。
  • YAML をサポートするあらゆる IDE を使用できます。
  • Red Hat は、Apache Camel in VS Code 用のエクステンションパックを提供しています。このパックには、VS Code で Red Hat build of Apache Camel を操作するために必要なエクステンションがすべて含まれています。これには、Camel K Java スタンドアロンの言語サポート、Camel URI 補完と診断のサポート、ソースエディターからの Camel ルートの実行とデバッグが含まれます。
  • 言語サポートと基本的な Camel テキストルートのデバッグ。
  • コード支援とルートデバッガーを提供します。
  • また、ビジュアル統合デザイナーを提供する Kaoto VS Code エクステンションも含まれています。

Hawtio/Fuse コンソール

Hawtio は、ルートの作成にどの DSL が使用されたかに関係なく、ランタイムからルートを XML として取得し、そのルートを表示します。

Hawtio は、ルートの作成にどの DSL が使用されたかに関係なく、ランタイムからルートを XML として取得し、そのルートを表示します。

Hawtio は、ルートの作成にどの DSL が使用されたかに関係なく、ランタイムからルートを XML として取得し、そのルートを表示します。

ソフトウェア開発モデル

DSL は、fluent builder API を採用しています。

  • グラフィカルエディターを使用したモデリング開発アプローチが可能です (Eclipse Desktop)。
  • ドラッグアンドドロップベースの開発を可能にします。
  • 成熟した IDE サポートにより、テキストベースの開発も可能です。

最初から書くのは困難です。グラフィカルエディターを使用したモデリング開発アプローチが可能です。

コードのデバッグ

  • EIP 上で段階的な DSL デバッグを提供する IDE プラグインがあります。RouteBuilder にステップインすることはできますが、これは起動時にのみ呼び出され、処理中は呼び出されません。
  • ブレークポイントは、コア Camel クラスの Java コードに設定できます。
  • 一時的なプロセッサーを追加し、Java デバッガーを使用することもできます。
  • EIP 上で段階的な DSL デバッグを提供する IDE プラグインがあります。
  • ブレークポイントは、コア Camel クラスの Java コードに設定できます。
  • EIP 上で段階的な DSL デバッグを提供する IDE プラグインがあります。
  • ブレークポイントは、コア Camel クラスの Java コードに設定できます。

依存性注入 (DI) フレームワークとの統合

あらゆる DI フレームワークとの統合が容易になります。

XML DSL で DI フレームワークから既存の Bean を参照することは可能ですが、XML で新しい Bean を宣言すると、これらの Bean は Camel 専用になり、DI フレームワーク (Quarkus や Spring Boot など) の一部ではなくなります。

YAML DSL で DI フレームワークから既存の Bean を参照することは可能ですが、YAML で新しい Bean を宣言すると、これらの Bean は Camel 専用になり、DI フレームワーク (Quarkus や Spring Boot など) の一部ではなくなります。

チーム規模

柔軟性は高くなりますが、コードが読みにくくなります。長期間にわたってコードの作業とサポートを行う、同一の場所にある小規模なチームに適しています。

  • 大規模で多様なチームに適しています。
  • 柔軟性が低いため、複雑なルートの作成が難しくなります。
  • 大規模で多様なチームに適しています。
  • 柔軟性が低いため、複雑なルートの作成が難しくなります。

チーム構造

Camel 統合を開発するには、チームに Java 開発者が必要です。他のチームメンバーも、統合フローを読み取るために Java を理解できる必要があります。

  • XML は広く普及している言語であり、Camel を使用して開発する際にすべての開発者が既存のスキルを再利用できます。
  • より高いレベルの抽象化を提供し、ビジネス開発者やサポートチームとのコミュニケーションを容易にします。
  • YAML は広く普及している言語であり、Camel を使用して開発する際にすべての開発者が既存のスキルを再利用できます。
  • より高いレベルの抽象化を提供し、ビジネス開発者やサポートチームとのコミュニケーションを容易にします。

開発者としての経験と好み

  • Java は XML よりも簡潔で、内部クラスと機能的な側面を備えているため、経験豊富な開発者に適しています。
  • Java 開発者は、XML よりも純粋な Java とアノテーションを好む傾向があります。

ルートを設計するためのグラフィカルなアプローチを提供しているため、新しいユーザーに最適です。

ルートを設計するためのグラフィカルなアプローチを提供しているため、新しいユーザーに最適です。

3.2. Spring Boot

Spring Boot は Camel を自動的に設定します。Camel コンテキストの独自の autoconfiguration は、Spring コンテキストで使用可能な Camel ルートを自動検出し、主要な Camel ユーティリティー (producer サーテンプレート、コンシューマーテンプレート、型コンバーターなど) を Bean として登録します。

Maven ユーザーは、このコンポーネントを使用するために pom.xml に次の依存関係を追加する必要があります。

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

camel-spring-boot jar には spring.factories ファイルが付属しているため、その依存関係をクラスパスに追加するとすぐに、Spring Boot によって Camel が自動的に設定されます。

3.2.1. Camel Spring Boot スターター

Apache Camel には、Spring Boot Starter モジュールが同梱されています。このモジュールを使用すると、スターターを使用して Spring Boot アプリケーションを開発できます。

サンプルリポジトリーには サンプルアプリケーション も用意されています。

スターターを使用するには、Spring Boot pom.xml ファイルに以下を追加します。

<dependency>
    <groupId>org.apache.camel.springboot</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.properties または application.yml ファイルで Camel アプリケーションをカスタマイズできます。

3.2.2. Spring Boot 自動設定

Spring Boot で spring-boot を使用する場合は、自動設定をサポートするために必ず次の Maven 依存関係を使用してください。

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

3.2.3. 自動設定された Camel コンテキスト

Camel 自動設定によって提供される最も重要な機能は、CamelContext インスタンスです。Camel 自動設定は、SpringCamelContext を作成し、そのコンテキストの適切な初期化とシャットダウンを処理します。作成された Camel コンテキストは、Spring アプリケーションコンテキストにも (camelContext Bean 名で) 登録されるため、他の Spring Bean と同じようにアクセスできます。

@Configuration
public class MyAppConfig {

  @Autowired
  CamelContext camelContext;

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

}
Copy to Clipboard Toggle word wrap

3.2.4. Camel ルートの自動検出

Camel 自動設定は、Spring コンテキストからすべての RouteBuilder インスタンスを収集し、提供された CamelContext にこれらのインスタンスを自動的に注入します。そのため、Spring Boot スターターを使用して新しい Camel ルートを作成するのは、@Component アノテーション付きクラスをクラスパスに追加するのと同じくらい簡単です。

@Component
public class MyRouter extends RouteBuilder {

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

}
Copy to Clipboard Toggle word wrap

または、新しいルートの RouteBuilder Bean を @Configuration クラスで作成します。

@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

3.2.5. Camel プロパティー

Spring Boot の自動設定は、Camel プロパティーのサポートを使用して Spring Boot 外部設定 (プロパティーのプレースホルダー、OS 環境変数、またはシステムプロパティーを含む) に自動的に接続します。そのため、基本的に、次のように 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

3.2.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

beforeApplicationStart メソッドは Spring コンテキストが開始される直前に呼び出されるため、このコールバックに渡される CamelContext インスタンスは完全に自動設定されます。CamelContextConfiguration の複数のインスタンスを Spring コンテキストに追加すると、各インスタンスが実行されます。

ヒント

サンプルアプリケーションは、camel-spring-boot-examples リポジトリーの Metrics の例を参照してください。

3.2.7. 自動設定されたコンシューマーおよびプロデューサーのテンプレート

Camel 自動設定によって、事前設定された ConsumerTemplate および ProducerTemplate インスタンスが提供されます。それらを 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.consumer-template-cache-size = 100
camel.springboot.producer-template-cache-size = 200
Copy to Clipboard Toggle word wrap

3.2.8. 自動設定された TypeConverter

Camel 自動設定では、Spring コンテキストの typeConverter という名前の TypeConverter インスタンスを登録します。

@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
3.2.8.1. Spring タイプコンバージョン API ブリッジ

Spring には、強力な タイプコンバージョン API が付属しています。Spring API は Camel の型コンバーター API と似ています。両方の API は非常に似ているため、Camel Spring Boot は、Spring コンバージョン API に委譲するブリッジコンバーター (SpringTypeConverter) を自動的に登録します。そのため、初期状態の Camel は Spring コンバーターを Camel コンバーターと同様に扱います。このアプローチでは、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

Camel Spring Boot は内部で、アプリケーションコンテキストで利用可能な Spring の ConversionService インスタンスに変換を委譲します。ConversionService インスタンスが利用できない場合は、Camel Spring Boot 自動設定によってインスタンスが作成されます。

ヒント

サンプルアプリケーションは、camel-spring-boot-examples リポジトリーの Type converter の例を参照してください。

3.2.9. アプリケーションの存続

この機能が有効になっている Camel アプリケーションは、JVM の終了を防止してアプリケーションを存続させることのみを目的として、起動時に新しいスレッドを起動します。つまり、Spring Boot で Camel アプリケーションを開始した後、アプリケーションは Ctrl+C シグナルを待機し、すぐには終了しません。

コントローラースレッドは、camel.springboot.main-run-controllertrue に設定することでアクティブ化できます。

camel.springboot.main-run-controller = true
Copy to Clipboard Toggle word wrap

Web モジュールを使用するアプリケーション (たとえば org.springframework.boot:spring-boot-web-starter モジュールをインポートするアプリケーション) は、他の非デーモンスレッドの存在によってアプリケーションが維持されるため、通常この機能を使用する必要はありません。

ヒント

サンプルアプリケーションは、camel-spring-boot-examples リポジトリーの POJO の例を参照してください。

3.2.10. XML ルートの追加

デフォルトでは、Camel XML ルートをディレクトリー camel の下のクラスパスに配置できます。このルートは、camel-spring-boot によって自動検出されて組み込まれます。設定オプションを使用すると、ディレクトリー名を設定したり、この機能を無効化できます。

# turn off
camel.springboot.routes-include-pattern = false
Copy to Clipboard Toggle word wrap
# scan only in the com/foo/routes classpath
camel.springboot.routes-include-pattern = classpath:com/foo/routes/*.xml
Copy to Clipboard Toggle word wrap

XML ファイルは、(<CamelContext> ではなく) 次のような Camel XML ルートである必要があります。

<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
ヒント

サンプルアプリケーションは、camel-spring-boot-examples リポジトリーの XML の例を参照してください。

3.2.11. JUnit 5 方式のテスト

テストのために、Maven ユーザーは次の依存関係を pom.xml に追加する必要があります。

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

Camel Spring Boot アプリケーションをテストするには、テストクラスに @CamelSpringBootTest のアノテーションを付けます。これにより、Camel の Spring Test サポートがアプリケーションに提供されるため、Spring Boot テスト規則 を使用してテストを作成できるようになります。

CamelContext または ProducerTemplate を取得するには、@Autowired を使用して、Spring の通常の方法でクラスに注入できます。

camel-test-spring-junit5 を使用して、テストを宣言的に設定することもできます。この例では、@MockEndpoints アノテーションを使用して、エンドポイントを自動モックします。

@CamelSpringBootTest
@SpringBootApplication
@MockEndpoints("direct:end")
public class MyApplicationTest {

    @Autowired
    private ProducerTemplate template;

    @EndpointInject("mock:direct:end")
    private MockEndpoint mock;

    @Test
    public void testReceive() throws Exception {
        mock.expectedBodiesReceived("Hello");
        template.sendBody("direct:start", "Hello");
        mock.assertIsSatisfied();
    }

}
Copy to Clipboard Toggle word wrap
ヒント

サンプルアプリケーションは、camel-spring-boot-examples リポジトリーの Infinispan の例を参照してください。

@CamelSpringBootTest@SpringBootTest の機能を継承します。これには、ルートテストユーティリティーの提供、CamelContext、ルートアドバイザー、およびモックエンドポイントの追加、Camel テストアノテーションの有効化、@MockEndpoints、@UseAdviceWith との連携といった機能が含まれます。

@UseAdviceWith の例としては、実行時にルートの変更が適用された場合が挙げられます。

package com.redhat;
 ....
import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 ....
@CamelSpringBootTest
@SpringBootApplication
public class MySpringBootApplicationTest {

	@Autowired
	private CamelContext camelContext;

	@Autowired
	private ProducerTemplate producerTemplate;

	public static void main(String[] args) {
		SpringApplication.run(MySpringBootApplicationTest.class, args);
	}

	// Spring context fixtures
	@Configuration
	static class TestConfig {

		@Bean
		RoutesBuilder route() {
			return new RouteBuilder() {
				@Override
				public void configure() throws Exception {
					from("timer:hello1?period={{timer.period}}").routeId("hello1")
							.transform().method("myBean", "saySomething")
							.filter(simple("${body} contains 'foo'"))
							.to("log:foo")
							.end()
							.to("stream:out");
				}
			};
		}
	}

	@Test
	public void test() throws Exception {
		// Apply advice before getting the mock endpoint
		AdviceWith.adviceWith(camelContext, "hello1",
				// intercepting an exchange on route
				r -> {
					// replacing consumer with direct component
					r.replaceFromWith("direct:start");
					// mocking producer
					r.mockEndpoints("stream*");
				}
		);

		// Start the context after applying advice
		camelContext.start();

		// Get mock endpoint after advice is applied
		MockEndpoint mock = camelContext.getEndpoint("mock:stream:out", MockEndpoint.class);

		// setting expectations
		mock.expectedMessageCount(1);
		mock.expectedBodiesReceived("Hello World");

		// invoking consumer
		producerTemplate.sendBody("direct:start", null);

		// asserting mock is satisfied
		mock.assertIsSatisfied();
	}
}
Copy to Clipboard Toggle word wrap

場合によっては、applicationContext が厳密に必要な場合は、@CamelSpringBootTest@SpringBootTest の両方の組み合わせを宣言する必要があります。その場合は、使用する設定クラスを指定する @SpringBootTest(classes = DocTest.TestApplication.class) を追加するだけです。

package com.redhat;
 ....
import org.apache.camel.EndpointInject;
import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
import org.apache.camel.test.spring.junit5.MockEndpoints;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 ....
@CamelSpringBootTest
@SpringBootTest(classes = MySpringBootApplicationTest.TestConfig.class)
@SpringBootApplication
@MockEndpoints("direct:end")
public class MySpringBootApplicationTest {

	@Autowired
	private ProducerTemplate template;

	@EndpointInject("mock:direct:end")
	private MockEndpoint mock;

	@Configuration
	static class TestConfig {

		@Bean
		RoutesBuilder route() {
			return new RouteBuilder() {
				@Override
				public void configure() throws Exception {
					from("direct:start").routeId("hello2")
							.setBody(simple("Hello World"))
							.log("Received: ${body}")
							.to("direct:end");

					from("direct:end")
							.log("${body}");
				}
			};
		}
	}

	@Test
	public void testReceive() throws Exception {
		mock.expectedMessageCount(1);
		mock.expectedBodiesReceived("Hello World");
		template.sendBody("direct:start", null);
		mock.assertIsSatisfied();
	}

}
Copy to Clipboard Toggle word wrap

もう 1 つのアプローチは、従来の Spring XML コンテキスト設定をテストすることです。この場合、@ContextConfiguration を使用して XML ファイルを指定し、依存性注入を使用してメイン Camel ランタイムコンテキストを取得する必要があります。

@Autowired
protected CamelContext camelContext;
Copy to Clipboard Toggle word wrap

次に、各テストメソッドの後に Spring ApplicationContext をリロードするには、次を使用します。

 @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
Copy to Clipboard Toggle word wrap

代替モード: BEFORE_CLASSAFTER_CLASSBEFORE_EACH_TEST_METHOD

完全な例を次に示します。

package com.redhat.plain;
 ....
import org.apache.camel.EndpointInject;
import org.apache.camel.Produce;
import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
 ....
@CamelSpringBootTest
@ContextConfiguration
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class MySpringBootApplicationPlainTest {

	@Autowired
	protected CamelContext camelContext;

	@EndpointInject("mock:a")
	protected MockEndpoint mockA;

	@Produce("direct:start")
	protected ProducerTemplate start;

	@Test
	public void testPositive() throws Exception {
		assertEquals(ServiceStatus.Started, camelContext.getStatus());
		start.sendBody("Hello");
		MockEndpoint.assertIsSatisfied(camelContext);
		mockA.expectedBodiesReceived("Hello");
	}
}
Copy to Clipboard Toggle word wrap

Spring XML コンテキストは、命名パターン className-context.xml を使用して、宣言されたクラスパッケージ com.redhat.plain のリソースに配置する必要があります。

プロジェクト構造

src/
├── main/ [yaml context structure]
│   ├── java/
│   │   └─── com/redhat/
│   │        ├── Application.java
│   │        └── route/
│   │            └── MyRoute.java
│   │
│   └── resources/
│       └── application.yml
└── test/ [xml context structure]
    ├── java/
    │   └─ com/redhat/plain
    │      ├── MySpringBootApplicationPlainTest.java
    │      └── route/
    │           └── MyRoute.java
    └── resources/
        └── com/redhat/plain
            └── MySpringBootApplicationPlainTest-context.xml
Copy to Clipboard Toggle word wrap

上記の例の XML 宣言:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
    ">

	<!-- Camel Context configuration -->
	<camelContext id="camelContext" xmlns="http://camel.apache.org/schema/spring">

		<route xmlns="http://camel.apache.org/schema/spring" id="helloX">
			<from id="from1" uri="direct:start"/>
			<filter id="filter1">
				<simple>${body} contains 'foo'</simple>
				<to id="to1" uri="log:foo"/>
			</filter>
			<to id="to2" uri="stream:out"/>
		</route>

	</camelContext>

</beans>
Copy to Clipboard Toggle word wrap

3.3. コンポーネントスターター

Camel Spring Boot は、Spring Boot スターターとして次の Camel アーティファクトをサポートします。

注記

Red Hat build of Apache Camel for Camel Spring Boot の BOM には、サポート対象およびサポート対象外のコンポーネントがリストされています。サポート対象コンポーネントの最新リストは、コンポーネントスターター を参照してください。

Expand
表3.1 Camel コンポーネント
コンポーネントアーティファクト説明IBM Power および IBM Z のサポート

AMQP

camel-amqp-starter

Apache QPid クライアントを使用した AMQP プロトコルによるメッセージング。

はい

AWS Cloudwatch

camel-aws2-cw-starter

AWS SDK バージョン 2.x を使用してメトリクスを AWS CloudWatch に送信します。

はい

AWS DynamoDB

camel-aws2-ddb-starter

AWS SDK バージョン 2.x を使用して、AWS DynamoDB サービスからデータを保存および取得します。

はい

AWS Kinesis

camel-aws2-kinesis-starter

AWS SDK バージョン 2.x を使用して、AWS Kinesis Streams からレコードを消費し、AWS Kinesis Streams にレコードを作成します。

はい

AWS Lambda

camel-aws2-lambda-starter

AWS SDK バージョン 2.x を使用して、AWS Lambda 関数を管理および呼び出します。

はい

AWS S3 Storage Service

camel-aws2-s3-starter

AWS SDK バージョン 2.x を使用して、AWS S3 Storage Service からオブジェクトを保存および取得します。

はい

AWS Simple Notification System (SNS)

camel-aws2-sns-starter

AWS SDK バージョン 2.x を使用して AWS Simple Notification Topic にメッセージを送信します。

はい

AWS Simple Queue Service (SQS)

camel-aws2-sqs-starter

AWS SDK バージョン 2.x を使用して AWS SQS サービスを送信先および送信元としてメッセージを送受信します。

はい

AWS Secrets Manager

camel-aws-secrets-manager-starter

AWS Secrets Manager を使用してシークレットを管理します。

はい

Azure Key Vault

camel-azure-key-vault-starter

Azure Key Vault サービスでシークレットとキーを管理する

はい

Azure ServiceBus

camel-azure-servicebus-starter

Azure Event Bus との間でメッセージを送受信します。

はい

Azure Storage Blob Service

camel-azure-storage-blob-starter

SDK v12 を使用して Azure Storage Blob Service からブロブを保存および取得します。

はい

Azure Storage Queue Service

camel-azure-storage-queue-starter

azure-storage-queue コンポーネントは、Azure SDK v12 を使用して Azure Storage Queue への/からのメッセージを保存および取得するために使用されます。

はい

Bean

camel-bean-starter

Camel レジストリーに格納されている Java Bean のメソッドを呼び出します。

はい

Bean Validator

camel-bean-validator-starter

Java Bean Validation API を使用してメッセージボディーを検証します。

はい

Browse

camel-browse-starter

BrowsableEndpoint をサポートするエンドポイントで受信したメッセージを調べます。

はい

Cassandra CQL

camel-cassandraql-starter

CQL3 API (Thrift API 以外) を使用して Cassandra 2.0 と統合します。DataStax が提供する Cassandra Java Driver をベースにしています。

はい

CICS

camel-cics-starter

CICS® 汎用トランザクション処理サブシステムと対話します。

いいえ

Control Bus

camel-controlbus-starter

Camel ルートを管理および監視します。

はい

Cron

camel-cron-starter

Unix cron 構文で指定されたタイミングでイベントをトリガーする汎用インターフェイス。

はい

Crypto (JCE)

camel-crypto-starter

Java Cryptographic Extension (JCE) の署名サービスを使用してエクスチェンジに署名し、検証します。

はい

CXF

camel-cxf-soap-starter

Apache CXF を使用して SOAP WebServices を公開するか、CXF WS クライアントを使用して外部 WebServices に接続します。

はい

CXF-RS

camel-cxf-rest-starter

Apache CXF を使用して JAX-RS REST サービスを公開するか、CXF REST クライアントを使用して外部の REST サービスに接続します。

はい

Data Format

camel-dataformat-starter

Camel Data Format を通常の Camel コンポーネントとして使用します。

はい

Dataset

camel-dataset-starter

Camel アプリケーションの負荷テストおよびソークテスト用のデータを提供します。

はい

Direct

camel-direct-starter

同じ Camel コンテキストから別のエンドポイントを同期的に呼び出します。

はい

Elastic Search

camel-elasticsearch-starter

Java クライアント API 経由で ElasticSearch にリクエストを送信します。

はい

FHIR

camel-fhir-starter

FHIR (Fast Healthcare Interoperability Resources) 規格を使用して、ヘルスケアドメインの情報を交換します。

いいえ

File

camel-file-starter

ファイルの読み取りと書き込みを行います。

はい

Flink

camel-flink-starter

DataSet ジョブを Apache Flink クラスターに送信します。

はい

FTP

camel-ftp-starter

FTP サーバーとの間でファイルをアップロードおよびダウンロードします。

はい

Google BigQuery

camel-google-bigquery-starter

分析用の Google BigQuery データウェアハウス。

はい

Google Pubsub

camel-google-pubsub-starter

Google Cloud Platform PubSub サービスとの間でメッセージを送受信します。

はい

Google Secret Manager

camel-google-secret-manager-starter

Google Secret Manager Secrets を管理する

はい

GraphQL

camel-graphql-starter

GraphQL クエリーとミューテーションを外部システムに送信します。

はい

gRPC

camel-grpc-starter

gRPC エンドポイントを公開し、外部 gRPC エンドポイントにアクセスします。

はい

Hashicorp Vault

camel-hashicorp-starter

Hashicorp Vault サービスでシークレットを管理します。

はい

HTTP

camel-http-starter

Apache HTTP Client 4.x を使用して、外部の HTTP サーバーにリクエストを送信します。

はい

Infinispan

camel-infinispan-starter

Infinispan の分散キー/値のストアとデータグリッドの読み取りと書き込みを行います。

いいえ

Infinispan Embedded

camel-infinispan-embedded-starter

Infinispan の分散キー/値のストアとデータグリッドの読み取りと書き込みを行います。

はい

JDBC

camel-jdbc-starter

SQL および JDBC を通じてデータベースにアクセスします。

はい

Jira

camel-jira-starter

JIRA 問題トラッカーと対話します。

はい

JMS

camel-jms-starter

JMS Queue または Topic との間でメッセージを送受信します。

はい

Jolokia

camel-jolokia-starter

Jolokia エージェント設定を Spring Boot に統合します。

はい

JPA

camel-jpa-starter

Java Persistence API (JPA) を使用して、データベースから Java オブジェクトを保存し、取得します。

はい

JSLT

camel-jslt-starter

JSLT を使用して JSON ペイロードをクエリーまたは変換します。

はい

Kafka

camel-kafka-starter

Apache Kafka ブローカーとの間でメッセージを送受信します。

はい

Kamelet

camel-kamelet-starter

Kamelets を呼び出します。

はい

Kubernetes の ConfigMap

camel-kubernetes-starter

Kubernetes ConfigMaps に対する操作を実行し、ConfigMaps の変更に関する通知を受け取ります。

はい

Kubernetes カスタムリソース

camel-kubernetes-starter

Kubernetes カスタムリソースに対する操作を実行し、デプロイメントの変更に関する通知を受け取ります。

はい

Kubernetes デプロイメント

camel-kubernetes-starter

Kubernetes デプロイメントに対する操作を実行し、デプロイメントの変更に関する通知を受け取ります。

はい

Kubernetes イベント

camel-kubernetes-starter

Kubernetes イベントに対する操作を実行し、イベントの変更に関する通知を受け取ります。

はい

Kubernetes HPA

camel-kubernetes-starter

Kubernetes Horizontal Pod Autoscaler (HPA) に対する操作を実行し、HPA の変更に関する通知を受け取ります。

はい

Kubernetes ジョブ

camel-kubernetes-starter

Kubernetes ジョブに対する操作を実行します。

はい

Kubernetes 名前空間

camel-kubernetes-starter

Kubernetes 名前空間に対する操作を実行し、名前空間の変更に関する通知を受け取ります。

はい

Kubernetes ノード

camel-kubernetes-starter

Kubernetes ノードに対する操作を実行し、ノードの変更に関する通知を受け取ります。

はい

Kubernetes 永続ボリューム

camel-kubernetes-starter

Kubernetes 永続ボリュームに対する操作を実行し、永続ボリュームの変更に関する通知を受け取ります。

はい

Kubernetes 永続ボリューム要求

camel-kubernetes-starter

Kubernetes 永続ボリューム要求に対する操作を実行し、永続ボリューム要求の変更に関する通知を受け取ります。

はい

Kubernetes Pod

camel-kubernetes-starter

Kubernetes Pod に対する操作を実行し、Pod の変更に関する通知を受け取ります。

はい

Kubernetes Replication Controller

camel-kubernetes-starter

はい。Kubernetes レプリケーションコントローラーに対する操作を実行し、レプリケーションコントローラーの変更に関する通知を受け取ります。

はい

Kubernetes リソースクォータ

camel-kubernetes-starter

Kubernetes リソースクォータに対する操作を実行します。

はい

Kubernetes Secrets

camel-kubernetes-starter

Kubernetes Secrets に対する操作を実行します。

はい

Kubernetes サービスアカウント

camel-kubernetes-starter

Kubernetes サービスアカウントに対する操作を実行します。

はい

Kubernetes サービス

camel-kubernetes-starter

Kubernetes サービスに対する操作を実行し、サービスの変更に関する通知を受け取ります。

はい

Kudu

camel-kudu-starter

Apache Hadoop エコシステムの無料およびオープンソースの列指向データストアである Apache Kudu と対話します。

いいえ

Language

camel-language-starter

Camel がサポートする任意の言語でスクリプトを実行します。

はい

LDAP

camel-ldap-starter

LDAP サーバーで検索を実行します。

はい

Log

camel-log-starter

基礎となるロギングメカニズムにメッセージをログとして記録します。

はい

LRA

camel-lra-starter

Long-Running-Action フレームワークの Camel saga バインディング。

はい

Mail

camel-mail-starter

imap、pop3、および smtp プロトコルを使用してメールを送受信します。

はい

Mail Microsoft OAuth

camel-mail-microsoft-oauth-starter

Camel Mail OAuth2 Authenticator for Microsoft Exchange Online。

はい

MapStruct

camel-mapstruct-starter

Mapstruct を使用した型変換。

はい

Master

camel-master-starter

クラスター内の単一のコンシューマーのみが特定のエンドポイントから消費するようにします。JVM が停止した場合に自動的にフェイルオーバーします。

はい

Micrometer

camel-micrometer-starter

Micrometer ライブラリーを使用して、Camel ルートからさまざまなメトリクスを直接収集します。

はい

Minio

camel-minio-starter

Minio SDK を使用して、Minio Storage Service からオブジェクトを保存および取得します。

はい

MLLP

camel-mllp-starter

MLLP プロトコルを使用して外部システムと通信します。

はい

Mock

camel-mock-starter

モックを使用してルートおよび仲介ルールをテストします。

はい

MongoDB

camel-mongodb-starter

MongoDB ドキュメントおよびコレクションの操作を実行します。

はい

MyBatis

camel-mybatis-starter

MyBatis を使用して、リレーショナルデータベースでクエリー、ポーリング、挿入、更新、または削除を実行します。

はい

Netty

camel-netty-starter

Netty 4.x で TCP または UDP を使用するソケットレベルのネットワーク。

はい

Observability Services

camel-observability-services

Camel 可観測性サービス

はい

Olingo4

camel-olingo4-starter

Apache Olingo OData API を使用して OData 4.0 サービスと通信します。

はい

OpenSearch

camel-opensearch-starter

Java Client API 経由で OpenSearch にリクエストを送信します。

はい

Openshift Builds

camel-kubernetes-starter

OpenShift Builds で操作を実行します。

はい

Openshift Deployment Configs

camel-kubernetes-starter

Openshift デプロイメント設定に対する操作を実行し、デプロイメント設定の変更に関する通知を受け取ります。

はい

Netty HTTP

camel-netty-http-starter

Netty 4.x を使用する Netty HTTP サーバーおよびクライアント。

はい

Paho

camel-paho-starter

Eclipse Paho MQTT クライアントを使用して MQTT メッセージブローカーと通信します。

はい

Paho MQTT 5

camel-paho-mqtt5-starter

Eclipse Paho MQTT v5 クライアントを使用して MQTT メッセージブローカーと通信します。

はい

Platform HTTP

camel-platform-http-starter

現在のプラットフォームで利用可能な HTTP サーバーを使用して HTTP エンドポイントを公開します。

はい

Quartz

camel-quartz-starter

Quartz 2.x スケジューラーを使用してメッセージの送信をスケジュールします。

はい

Ref

camel-ref-starter

Camel Registry で名前によって動的に検索されたエンドポイントにメッセージをルーティングします。

はい

REST

camel-rest-starter

REST サービスを公開するか、外部 REST サービスを呼び出します。

はい

Saga

camel-saga-starter

Saga EIP を使用して、ルート内でカスタムアクションを実行します。

はい

Salesforce

camel-salesforce-starter

Java DTO を使用して Salesforce と通信します。

はい

SAP

camel-sap-starter

SAP Java コネクター (SAP JCo) ライブラリーを使用して SAP との双方向通信を容易にし、SAP IDoc ライブラリーを使用して中間ドキュメント (IDoc) 形式でのドキュメントの送信を容易にします。

はい

Scheduler

camel-scheduler-starter

java.util.concurrent.ScheduledExecutorService を使用して、指定された間隔でメッセージを生成します。

はい

SEDA

camel-seda-starter

同じ JVM の Camel コンテキストから別のエンドポイントを非同期に呼び出します。

はい

Servlet

camel-servlet-starter

Servlet によって HTTP リクエストを処理します。

はい

Slack

camel-slack-starter

Slack との間でメッセージを送受信します。

はい

SMB

camel-smb-starter

SMB (Server Message Block) 共有からファイルを受信します。

はい

Smooks

camel-smooks-starter

Smooks を使用して、XML だけでなく、EDI、CSV、JSON、YAML などの XML 以外のデータを変換およびバインドします。

はい

SNMP

camel-snmp-starter

トラップを受信し、SNMP (Simple Network Management Protocol) 対応デバイスをポーリングします。

はい

Splunk

camel-splunk-starter

Splunk でイベントを公開または検索します。

いいえ

Spring Batch

camel-spring-batch-starter

さらに処理するためにメッセージを Spring Batch に送信します。

はい

Spring JDBC

camel-spring-jdbc-starter

Spring Transaction サポートにより、SQL および JDBC を介してデータベースにアクセスします。

はい

Spring LDAP

camel-spring-ldap-starter

メッセージペイロードとしてフィルターを使用して、LDAP サーバーで検索を実行します。

はい

Spring RabbitMQ

camel-spring-rabbitmq-starter

Spring RabbitMQ クライアントを使用して RabbitMQ からメッセージを送受信します。

はい

Spring Redis

camel-spring-redis-starter

Redis からメッセージを送受信します。

はい

Spring Webservice

camel-spring-ws-starter

このコンポーネントを使用して、Spring Web Services と統合できます。Web サービスにアクセスするためのクライアント側のサポート、およびコントラクトファースト Web サービスを作成するためのサーバー側のサポートを提供します。

はい

SQL

camel-sql-starter

Spring JDBC を使用して SQL クエリーを実行します。

はい

SQL ストアドプロシージャー

camel-sql-starter

Spring JDBC を使用して、SQL クエリーを JDBC ストアドプロシージャーとして実行します。

はい

SSH

camel-ssh-starter

SSH を使用してリモートホストでコマンドを実行します。

はい

Stub

camel-stub-starter

開発中またはテスト中に物理エンドポイントをスタブアウトします。

はい

Telegram

camel-telegram-starter

Telegram Bot API として動作するメッセージを送受信します。

はい

Timer

camel-timer-starter

java.util.Timer を使用して、指定された間隔でメッセージを生成します。

はい

Validator

camel-validator-starter

XML スキーマと JAXP 検証を使用してペイロードを検証します。

はい

Velocity

camel-velocity-starter

Velocity テンプレートを使用してメッセージを変換します。

はい

Vert.x HTTP クライアント

camel-vertx-http-starter

Vert.x を使用して、外部 HTTP サーバーにリクエストを送信します。

はい

Vert.x WebSocket

camel-vertx-websocket-starter

WebSocket エンドポイントを公開し、Vert.x を使用してリモート WebSocket サーバーに接続します。

はい

Webhook

camel-webhook-starter

Webhook エンドポイントを公開して、他の Camel コンポーネントのプッシュ通知を受信します。

はい

XJ

camel-xj-starter

XSLT を使用して、JSON および XML メッセージを変換します。

はい

XSLT

camel-xslt-starter

XSLT テンプレートを使用して XML ペイロードを変換します。

はい

XSLT Saxon

camel-xslt-saxon-starter

Saxon を使用した XSLT テンプレートを使用して XML ペイロードを変換します。

はい

Expand
表3.2 Camel データフォーマット
コンポーネントアーティファクト説明IBM Power および IBM Z のサポート

Avro

camel-avro-starter

Apache Avro バイナリーデータフォーマットを使用して、メッセージをシリアライズおよびデシリアライズします。

はい

Avro Jackson

camel-jackson-avro-starter

Jackson を使用して、POJO を Avro にマーシャリングし、その逆も行います。

はい

Bindy

camel-bindy-starter

Camel Bindy を使用して、POJO とキーと値のペア (KVP) 形式の間でマーシャリングおよびアンマーシャリングします。

はい

BeanIO

camel-beanio-starter

Java Bean をフラットファイル (CSV、区切り形式、固定長形式など) にマーシャリングおよびアンマーシャリングします。

はい

HL7

camel-hl7-starter

HL7 MLLP コーデックを使用して、HL7 (Health Care) モデルオブジェクトをマーシャリングおよびアンマーシャリングします。

はい

JacksonXML

camel-jacksonxml-starter

Jackson の XMLMapper エクステンションを使用して、XML ペイロードを POJO に、およびその逆にアンマーシャリングします。

はい

JAXB

camel-jaxb-starter

JAXB2 XML マーシャリング標準を使用して、XML ペイロードを POJO に、およびその逆にアンマーシャリングします。

はい

JSON Gson

camel-gson-starter

Gson を使用して、POJO を JSON に、およびその逆にマーシャリングします。

はい

JSON Jackson

camel-jackson-starter

Jackson を使用して、POJO を JSON にマーシャリングし、その逆も行います。

はい

Protobuf Jackson

camel-jackson-protobuf-starter

Jackson を使用して、POJO を Protobuf にマーシャリングし、その逆も行います。

はい

SOAP

camel-soap-starter

Java オブジェクトを SOAP メッセージにマーシャリングし、その逆も行います。

はい

Zip ファイル

camel-zipfile-starter

java.util.zip.ZipStream を使用して、ストリームを圧縮および圧縮解除します。

はい

Expand
表3.3 Camel 言語
言語アーティファクト説明IBM Power および IBM Z のサポート

Constant

camel-core-starter

固定の値は、ルートの起動時に一度だけ設定されます。

はい

CSimple

camel-core-starter

コンパイルされた単純な式を評価します。

はい

ExchangeProperty

camel-core-starter

Exchange からプロパティーを取得します。

はい

File

camel-core-starter

Simple 言語のファイル関連機能。

はい

Groovy

camel-groovy-starter

Groovy スクリプトを評価します。

はい

Header

camel-core-starter

Exchange からヘッダーを取得します。

はい

JQ

camel-jq-starter

JQ 式を JSON メッセージボディーに対して評価します。

はい

JSONPath

camel-jsonpath-starter

JSON メッセージのボディーに対して、JSONPath 式を評価します。

はい

Ref

camel-core-starter

レジストリーの既存の式を使用します。

はい

Simple

camel-core-starter

Camel 単純式を評価します。

はい

Tokenize

camel-core-starter

区切り文字パターンを使用してテキストペイロードをトークン化します。

はい

XML Tokenize

camel-xml-jaxp-starter

XML ペイロードをトークン化します。

はい

XPath

camel-xpath-starter

XML ペイロードに対して XPath 式を評価します。

はい

XQuery

camel-saxon-starter

XQuery および Saxon を使用して XML ペイロードをクエリーまたは変換します。

はい

Expand
表3.4 その他のエクステンション
エクステンションアーティファクト説明IBM Power および IBM Z のサポート

Jasypt

camel-jasypt-starter

Jasypt を使用したセキュリティー

はい

Kamelet Main

camel-kamelet-main-starter

Kamelet スタンドアロンを実行するためのメイン

はい

Openapi Java

camel-openapi-java-starter

openapi ドキュメントを使用するための REST-dsl サポート

はい

OpenTelemetry

camel-opentelemetry-starter

OpenTelemetry を使用した分散トレース

はい

Spring Security

camel-spring-security-starter

Spring Security を使用したセキュリティー

はい

YAML DSL

camel-yaml-dsl-starter

YAML を使用した Camel DSL

はい

3.4. スターター設定

明確でアクセスしやすい設定は、アプリケーションの重要な部分です。Camel スターター は、Spring Boot の 外部設定 メカニズムを完全にサポートします。より複雑なユースケースでは、Spring Bean を介してこのようなスターター設定することもできます。

3.4.1. 外部設定の使用

内部的には、すべての スターター は Spring Boot の ConfigurationProperties を介して設定されます。各設定パラメーターは、さまざまな 方法 で設定できます (application.[properties|json|yaml] ファイル、コマンドライン引数、環境変数など)。パラメーターの形式は camel.[component|language|dataformat].[name].[parameter] です。

たとえば、MQTT5 ブローカーの URL を設定するには、次のように設定できます。

camel.component.paho-mqtt5.broker-url=tcp://localhost:61616
Copy to Clipboard Toggle word wrap

また、CSV データフォーマットの delimeter をセミコロン (;) にするように設定することも可能です。

camel.dataformat.csv.delimiter=;
Copy to Clipboard Toggle word wrap

Camel は、プロパティーを目的のタイプに設定するときに、型コンバーター メカニズムを使用します。

#bean:name を使用して、レジストリー内の Bean を参照できます。

camel.component.jms.transactionManager=#bean:myjtaTransactionManager
Copy to Clipboard Toggle word wrap

通常、Bean は Java で作成されます。

@Bean("myjtaTransactionManager")
public JmsTransactionManager myjtaTransactionManager(PooledConnectionFactory pool) {
    JmsTransactionManager manager = new JmsTransactionManager(pool);
    manager.setDefaultTimeout(45);
    return manager;
}
Copy to Clipboard Toggle word wrap

Bean は 設定ファイル で作成することもできますが、これは複雑なユースケースには推奨されません。

3.4.2. Bean の使用

スターターは、Spring Bean を介して作成および設定することもできます。スターターを作成する前に、すでに存在する場合、Camel は最初にその名前でレジストリーを検索します。たとえば、Kafka コンポーネントを設定するには、次のようにします。

@Bean("kafka")
public KafkaComponent kafka(KafkaConfiguration kafkaconfiguration){
    return ComponentsBuilderFactory.kafka()
                        .brokers("{{kafka.host}}:{{kafka.port}}")
                        .build();
}
Copy to Clipboard Toggle word wrap

Bean 名は、設定するコンポーネント、データ形式、または言語の名前と同じである必要があります。Bean 名がアノテーションで指定されていない場合は、メソッド名に設定されます。

一般的な Camel Spring Boot プロジェクトでは、外部設定と Bean の組み合わせを使用してアプリケーションを設定します。Camel Spring Boot プロジェクトを設定する方法の詳細な例は、examples repository を参照してください。

3.5. Maven を使用した Spring Boot アプリケーション用の Camel 生成

Maven アーキタイプ org.apache.camel.archetypes:camel-archetype-spring-boot:4.10.7.redhat-00013 を使用して、Red Hat build of Apache Camel for Spring Boot アプリケーションを生成できます。

手順

  1. 以下のコマンドを実行します。

    mvn archetype:generate \
     -DarchetypeGroupId=org.apache.camel.archetypes \
     -DarchetypeArtifactId=camel-archetype-spring-boot \
     -DarchetypeVersion=4.10.7.redhat-00013 \
     -DgroupId=com.redhat \
     -DartifactId=csb-app \
     -Dversion=1.0-SNAPSHOT \
     -DinteractiveMode=false
    Copy to Clipboard Toggle word wrap
  2. アプリケーションをビルドします。

    mvn package -f csb-app/pom.xml
    Copy to Clipboard Toggle word wrap
  3. アプリケーションを実行します。

    java -jar csb-app/target/csb-app-1.0-SNAPSHOT.jar
    Copy to Clipboard Toggle word wrap
  4. アプリケーションによって生成された Hello World 出力のコンソールログを調べて、アプリケーションが実行されていることを確認します。

    com.redhat.MySpringBootApplication       : Started MySpringBootApplication in 3.514 seconds (JVM running for 4.006)
    Hello World
    Hello World
    Copy to Clipboard Toggle word wrap

Spring Boot 上の Apache Camel のコードを移行する場合は頻繁に、新しい Camel API の変更に適応し、クラスの名前を変更する必要があります。これを解決するには、OpenRewrite に基づく Camel 更新レシピを使用できます。これらのレシピは手動による移行を支援し、効率化を図ります。

Camel JBang を使用して、Red Hat build of Apache Camel on Spring Boot アプリケーションを更新できます。Camel JBang は、camel update コマンドを提供します。主な操作は 2 つあります。

  • run: 実際の更新プロセスを実行する

更新プロセスでは Apache Camel Open Rewrite レシピ が使用されます。次のアプリケーションタイプをサポートします。

  • Plain Camel (camel-main)
  • Camel Quarkus
  • Camel Spring Boot (Spring Boot で実行)

ここで、Camel および Camel Spring Boot の更新では主に camel-upgrade-recipes が使用され、Camel Quarkus の更新では Quarkus ランタイム (Rewrite Quarkus 経由) と Apache Camel レシピの両方を利用します。

3.6.1. Camel 更新の実行

このバージョンへの更新を実行するには、次を使用します。

$ camel update run {camelSpringBootVersion} --runtime=spring-boot
Copy to Clipboard Toggle word wrap
注記

更新コマンドは、pom.xml ファイルが含まれているプロジェクトディレクトリーで実行する必要があります。

3.6.1.1. 設定オプション

利用可能ないくつかのオプションを使用して更新プロセスをカスタマイズできます。

  • --runtime: アプリケーションの種類を指定します。

    • spring-boot - Camel Spring Boot アプリケーション
  • --repos: 更新中に使用する追加の Maven リポジトリー
  • --dry-run: 変更を適用せずにプレビューする
  • --extraActiveRecipes: 適用する追加のレシピ名のコンマ区切りリスト
  • --extraRecipeArtifactCoordinates: 追加レシピの Maven 座標のコンマ区切りリスト (形式: groupId:artifactId:version)
  • --help: 利用可能なすべてのオプションを表示します。
3.6.1.2. 通常の Camel アプリケーションの更新

次の例は、通常の Camel アプリケーションを更新する方法を示しています。

$ camel update run 4.10.7.redhat-00013 --runtime=camel-main --repos=https://myMaven/repo --extraActiveRecipes=my.first.Recipe,my.second.Recipe --extraRecipeArtifactCoordinates=ex.my.org:recipes:1.0.0
Copy to Clipboard Toggle word wrap
3.6.1.3. Spring Boot アプリケーションの更新

次のコマンドを使用して、Spring Boot アプリケーションを更新できます。-extraActiveRecipes オプションを使用して、追加の Spring Boot アップグレードを実行できます。

$ camel update run 4.10.7.redhat-00013 --runtime=spring-boot --extraActiveRecipes=org.openrewrite.java.spring.boot3.UpgradeSpringBoot_3_3 --extraRecipeArtifactCoordinates=org.openrewrite.recipe:rewrite-spring:6.0.2
Copy to Clipboard Toggle word wrap

3.7. Camel Spring Boot アプリケーションの OpenShift へのデプロイ

このガイドでは、Camel Spring Boot アプリケーションを OpenShift にデプロイする方法を説明します。

前提条件

  • OpenShift クラスターにアクセスできる。
  • OpenShift oc CLI クライアントがインストールされている、または OpenShift Container Platform Web コンソールにアクセスできる。
注記

認定 OpenShift Container プラットフォームは、Camel for Spring Boot Supported Configurations にリストされています。次の例では、Red Hat OpenJDK 11 (ubi8/openjdk-11) コンテナーイメージを使用しています。

手順

  1. このガイドのセクション 1.5 Maven を使用した Spring Boot アプリケーション用の Camel 生成 の手順に従って、Maven を使用して Spring Boot アプリケーション用の Camel を生成します。
  2. 修正した pom.xml が存在するディレクトリー配下で以下のコマンドを実行します。

    mvn clean -DskipTests oc:deploy -Popenshift
    Copy to Clipboard Toggle word wrap
  3. CSB アプリケーションが Pod 上で実行されていることを確認します。

    oc logs -f dc/csb-app
    Copy to Clipboard Toggle word wrap

3.8. Red Hat build of Apache Camel for Spring Boot へのパッチ適用

新しい patch-maven-plugin メカニズムを使用すると、Red Hat Red Hat build of Apache Camel for Spring Boot アプリケーションにパッチを適用できます。このメカニズムを使用すると、異なる Red Hat アプリケーション BOM によって提供される個々のバージョン (camel-spring-boot-bom など) を変更できます。

patch-maven-plugin の目的は、Camel on Spring Boot BOM にリストされている依存関係のバージョンを、アプリケーションに適用するパッチのメタデータで指定されているバージョンに更新することです。

patch-maven-plugin は次の操作を実行します。

  • 現在の Red Hat アプリケーション BOM に関連するパッチのメタデータを取得します。
  • BOM からインポートされた <dependencyManagement> にバージョンの変更を適用します。

patch-maven-plugin は、メタデータを取得すると、プラグインが宣言されたプロジェクトの管理対象および直接の依存関係すべてに対して繰り返し処理を行い、CVE/パッチのメタデータを使用して、一致する依存関係バージョンを置き換えます。バージョンが置き換えられると、Maven ビルドが続行され、標準の Maven プロジェクトのステージに進みます。

手順

以下の手順では、アプリケーションにパッチを適用する方法を説明します。

  1. patch-maven-plugin をプロジェクトの pom.xml ファイルに追加します。patch-maven-plugin のバージョンは、Camel on Spring Boot BOM のバージョンと同じである必要があります。

    <build>
        <plugins>
            <<plugin>
                <groupId>com.redhat.camel.springboot.platform</groupId>
                <artifactId>patch-maven-plugin</artifactId>
                <version>${camel-spring-boot-version}</version>
                <extensions>true</extensions>
            </plugin>
        </plugins>
    </build>
    Copy to Clipboard Toggle word wrap
  2. mvn clean deploymvn validate、または mvn dependency:tree コマンドのいずれかを実行すると、プラグインはプロジェクトモジュールを検索して、モジュールが Red Hat build of Apache Camel for Spring Boot BOM を使用しているかどうかを確認します。サポートされている BOM は次のとおりです。

    • com.redhat.camel.springboot.platform:camel-spring-boot-bom: Red Hat build of Apache Camel for Spring Boot BOM 用
  3. プラグインは、上記の BOM を検出できない場合、次のメッセージを表示します。

    $ mvn clean install
    
    [INFO] Scanning for projects...
    [INFO]
    
    ========== Red Hat Maven patching ==========
    
    [INFO] [PATCH] No project in the reactor uses Camel on Spring Boot product BOM. Skipping patch processing.
    [INFO] [PATCH] Done in 7ms
    
    =================================================
    Copy to Clipboard Toggle word wrap
  4. 正しい BOM が使用されている場合、パッチのメタデータが検出されますが、パッチは検出されません。

    $ mvn clean install
    
    [INFO] Scanning for projects...
    [INFO]
    
    ========== Red Hat Maven patching ==========
    
    [INFO] [PATCH] Reading patch metadata and artifacts from 2 project repositories
    [INFO] [PATCH]  - redhat-ga-repository: http://maven.repository.redhat.com/ga/
    [INFO] [PATCH]  - central: https://repo.maven.apache.org/maven2
    Downloading from redhat-ga-repository: http://maven.repository.redhat.com/ga/com/redhat/camel/springboot/platform/redhat-camel-spring-boot-patch-metadata/maven-metadata.xml
    Downloading from central: https://repo.maven.apache.org/maven2/com/redhat/camel/springboot/platform/redhat-camel-spring-boot-patch-metadata/maven-metadata.xml
    [INFO] [PATCH] Resolved patch descriptor: /path/to/.m2/repository/com/redhat/camel/springboot/platform/redhat-camel-spring-boot-patch-metadata/3.20.1.redhat-00043/redhat-camel-spring-boot-patch-metadata-3.20.1.redhat-00043.xml
    [INFO] [PATCH] Patch metadata found for com.redhat.camel.springboot.platform/camel-spring-boot-bom/[3.20,3.21)
    [INFO] [PATCH] Done in 938ms
    
    =================================================
    Copy to Clipboard Toggle word wrap
  5. patch-maven-plugin は、この Maven メタデータを取得しようとします。

    • Camel Spring Boot BOM を含むプロジェクトの場合、com.redhat.camel.springboot.platform:redhat-camel-spring-boot-patch-metadata/maven-metadata.xml が解決されます。この XML データは、com.redhat.camel.springboot.platform:redhat-camel-spring-boot-patch-metadata:RELEASE 座標を持つアーティファクトのメタデータです。

      Maven によって生成されたメタデータの例

      <?xml version="1.0" encoding="UTF-8"?>
      <metadata>
        <groupId>com.redhat.camel.springboot.platform</groupId>
        <artifactId>redhat-camel-spring-boot-patch-metadata</artifactId>
        <versioning>
          <release>3.20.1.redhat-00041</release>
          <versions>
            <version>3.20.1.redhat-00041</version>
          </versions>
          <lastUpdated>20230322103858</lastUpdated>
        </versioning>
      </metadata>
      Copy to Clipboard Toggle word wrap

  6. patch-maven-plugin は、メタデータを解析して、現在のプロジェクトに適用するバージョンを選択します。このアクションは特定のバージョンの Camel on Spring Boot BOM を使用する Maven プロジェクトのみで可能です。バージョン範囲以降に一致するメタデータのみが適用され、最新バージョンのメタデータのみが取得されます。
  7. patch-maven-plugin は、前の手順で見つかった groupIdartifactId、および version によって識別されるパッチのメタデータをダウンロードするためのリモート Maven リポジトリーのリストを収集します。これらの Maven リポジトリーは、アクティブなプロファイル内のプロジェクトの <repositories> 要素にリストされ、また settings.xml ファイルのリポジトリーにもリストされます。

    $ mvn clean install
    [INFO] Scanning for projects...
    [INFO]
    
    ========== Red Hat Maven patching ==========
    
    [INFO] [PATCH] Reading patch metadata and artifacts from 2 project repositories
    [INFO] [PATCH]  - MRRC-GA: https://maven.repository.redhat.com/ga
    [INFO] [PATCH]  - central: https://repo.maven.apache.org/maven2
    Copy to Clipboard Toggle word wrap
  8. メタデータは、リモートリポジトリー、ローカルリポジトリー、または ZIP ファイルから取得されたものであっても、patch-maven-plugin によって分析されます。取得されたメタデータには CVE のリストが含まれており、CVE ごとに、影響を受ける Maven アーティファクト (glob パターンとバージョン範囲で指定) のリストと、指定の CVE に対する修正を含むバージョンが記載されています。以下に例を示します。

    <?xml version="1.0" encoding="UTF-8" ?>
    
    <<metadata xmlns="urn:redhat:patch-metadata:1">
        <product-bom groupId="com.redhat.camel.springboot.platform" artifactId="camel-spring-boot-bom" versions="[3.20,3.21)" />
        <cves>
        </cves>
        <fixes>
            <fix id="HF0-1" description="logback-classic (Example) - Version Bump">
                <affects groupId="ch.qos.logback" artifactId="logback-classic" versions="[1.0,1.3.0)" fix="1.3.0" />
            </fix>
        </fixes>
    </metadata>
    Copy to Clipboard Toggle word wrap
  9. 最後に、現在のプロジェクトに含まれるすべての管理対象の依存関係に繰り返し処理を行うときに、パッチのメタデータで指定された修正のリストが参照されます。これらの依存関係のうち一致するもの (および管理対象の依存関係) が、固定バージョンに変更されます。以下に例を示します。

    $ mvn dependency:tree
    
    [INFO] Scanning for projects...
    [INFO]
    
    ========== Red Hat Maven patching ==========
    
    [INFO] [PATCH] Reading patch metadata and artifacts from 3 project repositories
    [INFO] [PATCH]  - redhat-ga-repository: http://maven.repository.redhat.com/ga/
    [INFO] [PATCH]  - local: file:///path/to/.m2/repository
    [INFO] [PATCH]  - central: https://repo.maven.apache.org/maven2
    [INFO] [PATCH] Resolved patch descriptor:/path/to/.m2/repository/com/redhat/camel/springboot/platform/redhat-camel-spring-boot-patch-metadata/3.20.1.redhat-00043/redhat-camel-spring-boot-patch-metadata-3.20.1.redhat-00043.xml
    [INFO] [PATCH] Patch metadata found for com.redhat.camel.springboot.platform/camel-spring-boot-bom/[3.20,3.21)
    [INFO] [PATCH]  - patch contains 1 patch fix
    [INFO] [PATCH] Processing managed dependencies to apply patch fixes...
    [INFO] [PATCH] - HF0-1: logback-classic (Example) - Version Bump
    [INFO] [PATCH]   Applying change ch.qos.logback/logback-classic/[1.0,1.3.0) -> 1.3.0
    [INFO] [PATCH]   Project com.test:yaml-routes
    [INFO] [PATCH]    - managed dependency: ch.qos.logback/logback-classic/1.2.11 -> 1.3.0
    [INFO] [PATCH] Done in 39ms
    
    =================================================
    Copy to Clipboard Toggle word wrap

パッチのスキップ

特定のパッチをプロジェクトに適用する必要がない場合、patch-maven-plugin には skip オプションが用意されています。patch-maven-plugin をプロジェクトの pom.xml ファイルにすでに追加しており、バージョンを変更する必要がない場合は、次のいずれかの方法を使用してパッチをスキップできます。

  • 以下のように、プロジェクトの pom.xml ファイルに skip オプションを追加します。
<build>
    <plugins>
        <plugin>
            <groupId>com.redhat.camel.springboot.platform</groupId>
            <artifactId>patch-maven-plugin</artifactId>
            <version>${camel-spring-boot-version}</version>
            <extensions>true</extensions>
            <configuration>
                <skip>true</skip>
            </configuration>
        </plugin>
    </plugins>
</build>
Copy to Clipboard Toggle word wrap
  • または、以下のように mvn コマンドの実行時に -DskipPatch オプションを使用します。
$ mvn clean install -DskipPatch
[INFO] Scanning for projects...
[INFO]
[INFO] -------------------------< com.example:test-csb >-------------------------
[INFO] Building A Camel Spring Boot Route 1.0-SNAPSHOT
...
Copy to Clipboard Toggle word wrap

上記の出力にあるように、patch-maven-plugin は呼び出されず、パッチはアプリケーションに適用されません。

3.9. Camel REST DSL OpenApi Maven プラグイン

Camel REST DSL OpenApi Maven プラグインは、次の目的をサポートします。

  • camel-restdsl-openapi:generate - OpenApi 仕様からコンシューマー REST DSL RouteBuilder ソースコードを生成する
  • camel-restdsl-openapi:generate-with-dto - OpenApi 仕様から、swagger-codegen-maven-plugin 経由で生成された DTO モデルクラスを使用してコンシューマー REST DSL RouteBuilder ソースコードを生成する
  • camel-restdsl-openapi:generate-xml - OpenApi 仕様からコンシューマー REST DSL XML ソースコードを生成する
  • camel-restdsl-openapi:generate-xml-with-dto - OpenApi 仕様から、swagger-codegen-maven-plugin 経由で生成された DTO モデルクラスを使用してコンシューマー REST DSL XML ソースコードを生成する
  • camel-restdsl-openapi:generate-yaml - OpenApi 仕様からコンシューマー REST DSL YAML ソースコードを生成する
  • camel-restdsl-openapi:generate-yaml-with-dto - OpenApi 仕様から、swagger-codegen-maven-plugin 経由で生成された DTO モデルクラスを使用してコンシューマー REST DSL YAML ソースコードを生成する

3.9.1. Maven pom.xml へのプラグインの追加

このプラグインは、Spring Boot アプリケーションなどの plugins セクションに追加することで、Maven pom.xml ファイルに追加できます。

<build>
  <plugins>
    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>

    <plugin>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-restdsl-openapi-plugin</artifactId>
      <version>{CamelCommunityVersion}</version>
    </plugin>

  </plugins>
</build>
Copy to Clipboard Toggle word wrap

次に、以下に示すように、接頭辞 camel-restdsl-openapi を使用してプラグインを実行できます。

$mvn camel-restdsl-openapi:generate
Copy to Clipboard Toggle word wrap

3.9.2. camel-restdsl-openapi:generate

Camel REST DSL OpenApi Maven プラグインの目的は、Maven から REST DSL RouteBuilder 実装ソースコードを生成するために使用されます。

3.9.2.1. オプション

プラグインは、コマンドラインから設定するか (-D 構文を使用)、configuration タグの pom.xml ファイルに定義できる次のオプションをサポートします。

Expand
パラメーターデフォルト値説明

skip

false

コード生成をスキップするには、true に設定します。

filterOperation

 

指定された操作 ID のみを含めるために使用されます。複数の ID はコンマで区切ることができます。ワイルドカードを使用できます。たとえば、find* を使用して、find で始まるすべての操作を含めることができます。

specificationUri

src/spec/openapi.json

OpenApi 仕様の URI は、ファイルシステムパス、HTTP およびクラスパスリソースをサポートします。デフォルトでは、プロジェクトディレクトリー内の src/spec/openapi.json です。JSON と YAML をサポートします。

auth

 

OpenApi 仕様定義をリモートで取得するときに認証ヘッダーを追加します。複数の値をコンマで区切って、name:header の URL エンコード文字列を渡します。

className

title または RestDslRoute から

生成されたクラスの名前。OpenApi 仕様のタイトルから取得されるか、デフォルトで RestDslRoute に設定されます。

packageName

host または rest.dsl.generated から

生成されたクラスのパッケージの名前。OpenApi 仕様のホスト値またはデフォルトで rest.dsl.generated から取得されます。

indent

" "

使用するインデント文字 (デフォルトでは 4 つのスペース)、\t を使用してタブ文字を表すことができます。

outputDirectory

generated-sources/restdsl-openapi

生成されたソースファイルを配置する場所。デフォルトでは、プロジェクトディレクトリー内の generated-sources/restdsl-openapi

destinationGenerator

 

宛先エンドポイントをカスタマイズするための org.apache.camel.generator.openapi.DestinationGenerator インターフェイスを実装するクラスの完全修飾クラス名

destinationToSyntax

direct:${operationId}

to uri のデフォルトの to 構文では、direct コンポーネントが使用されます。

restConfiguration

true

検出された残りコンポーネントを使用した残り設定の生成を含めるかどうか。

apiContextPath

 

restConfiguration が true に設定されている場合は、openapi エンドポイントパスを定義します。

clientRequestValidation

false

リクエストの検証を有効にするかどうか。

basePath

 

OpenAPI 仕様で定義されている API ベースパスをオーバーライドします。

requestMappingValues

/**

カスタム RequestMapping マッピング値の生成を許可します。複数のマッピング値は次のように渡すことができます。

<requestMappingValues> <param>/my-api-path/</param> <param>/my-other-path/</param> </requestMappingValues>

3.9.3. サーブレットコンポーネントを含む Spring Boot プロジェクト

Maven プロジェクトが Spring Boot プロジェクトであり、restConfiguration が有効で、サーブレットコンポーネントが REST コンポーネントとして使用されている場合、このプラグインは @SpringBootApplication メインクラスが配置されているパッケージ名 (packageName が明示的に設定されていない場合) を自動検出します。そして、Rest DSL ソースコードと必要な CamelRestController サポートクラスの生成に同じパッケージ名を使用します。

3.9.4. camel-restdsl-openapi:generate-with-dto

generate ゴールとして機能しますが、swagger-codegen-maven-plugin を自動的に実行して OpenApi 仕様から DTO モデルクラスの Java ソースコードを生成することにより、DTO モデルクラスも生成します。

このプラグインは、モデル DTO を生成するために swagger-codegen-maven-plugin を使用するためのデフォルトの優れた努力セットのみをサポートするように範囲が定められ、制限されています。さらなるパワーと柔軟性が必要な場合は、このプラグインではなく、Swagger Codegen Maven プラグイン を直接使用して DTO を生成します。

DTO クラスには、次のような追加の依存関係が必要になる場合があります。

    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.10.1</version>
    </dependency>
    <dependency>
      <groupId>io.swagger.core.v3</groupId>
      <artifactId>swagger-core</artifactId>
      <version>2.2.8</version>
    </dependency>
    <dependency>
      <groupId>org.threeten</groupId>
      <artifactId>threetenbp</artifactId>
      <version>1.6.8</version>
    </dependency>
Copy to Clipboard Toggle word wrap
3.9.4.1. オプション

プラグインは次の 追加 オプションをサポートしています。

Expand
パラメーターデフォルト値説明

swaggerCodegenMavenPluginVersion

3.0.36

使用する io.swagger.codegen.v3:swagger-codegen-maven-plugin Maven プラグインのバージョン。

modelOutput

 

ターゲット出力パス (デフォルトは ${project.build.directory}/generated-sources/openapi)

modelPackage

io.swagger.client.model

生成されたモデルオブジェクト/クラスに使用するパッケージ

modelNamePrefix

 

モデルクラスと列挙型の接頭辞または接尾辞を設定します。

modelNameSuffix

 

モデルクラスと列挙型の接頭辞または接尾辞を設定します。

modelWithXml

false

生成されたモデル内で XML アノテーションを有効にします (JSON および XML のサポートを提供するライブラリーのみで機能)。

configOptions

 

言語固有のパラメーターのマップを swagger-codegen-maven-plugin に渡します。

3.9.5. camel-restdsl-openapi:generate-xml

Camel REST DSL OpenApi Maven プラグインの camel-restdsl-openapi:generate-xml ゴールは、Maven から REST DSL XML 実装ソースコードを生成するために使用されます。

3.9.5.1. オプション

プラグインは、コマンドラインから設定するか (-D 構文を使用)、<configuration> タグの pom.xml ファイルに定義できる次のオプションをサポートします。

Expand
パラメーターデフォルト値説明

skip

false

コード生成をスキップするには、true に設定します。

filterOperation

 

指定された操作 ID のみを含めるために使用されます。複数の ID はコンマで区切ることができます。ワイルドカードを使用できます。たとえば、find* を使用して、find で始まるすべての操作を含めることができます。

specificationUri

src/spec/openapi.json

OpenApi 仕様の URI は、ファイルシステムパス、HTTP およびクラスパスリソースをサポートします。デフォルトでは、プロジェクトディレクトリー内の src/spec/openapi.json です。JSON と YAML をサポートします。

auth

 

OpenApi 仕様定義をリモートで取得するときに認証ヘッダーを追加します。複数の値をコンマで区切って、name:header の URL エンコード文字列を渡します。

outputDirectory

generated-sources/restdsl-openapi

生成されたソースファイルを配置する場所。デフォルトでは、プロジェクトディレクトリー内の generated-sources/restdsl-openapi

fileName

camel-rest.xml

出力としての XML ファイルの名前。

blueprint

false

有効にすると、Spring XML の代わりに OSGi Blueprint XML が生成されます。

destinationGenerator

 

宛先エンドポイントをカスタマイズするための org.apache.camel.generator.openapi.DestinationGenerator インターフェイスを実装するクラスの完全修飾クラス名

destinationToSyntax

direct:${operationId}

to uri のデフォルトの to 構文では、direct コンポーネントが使用されます。

 

restConfiguration

true

検出された残りコンポーネントを使用した残り設定の生成を含めるかどうか。

apiContextPath

 

restConfigurationtrue に設定されている場合は、openapi エンドポイントパスを定義します。

clientRequestValidation

false

リクエストの検証を有効にするかどうか。

basePath

 

OpenAPI 仕様で定義されている API ベースパスをオーバーライドします。

requestMappingValues

/**

3.9.6. camel-restdsl-openapi:generate-xml-with-dto

generate-xml ゴールとして機能しますが、swagger-codegen-maven-plugin を自動的に実行して OpenApi 仕様から DTO モデルクラスの Java ソースコードを生成することにより、DTO モデルクラスも生成します。

このプラグインは、モデル DTO を生成するために swagger-codegen-maven-plugin を使用するためのデフォルトの優れた努力セットのみをサポートするように範囲が定められ、制限されています。さらなるパワーと柔軟性が必要な場合は、このプラグインではなく、Swagger Codegen Maven プラグイン を直接使用して DTO を生成します。

DTO クラスには、次のような追加の依存関係が必要になる場合があります。

    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.10.1</version>
    </dependency>
    <dependency>
      <groupId>io.swagger.core.v3</groupId>
      <artifactId>swagger-core</artifactId>
      <version>2.2.8</version>
    </dependency>
    <dependency>
      <groupId>org.threeten</groupId>
      <artifactId>threetenbp</artifactId>
      <version>1.6.8</version>
    </dependency>
Copy to Clipboard Toggle word wrap
3.9.6.1. オプション

プラグインは次の 追加 オプションをサポートしています。

Expand
パラメーターデフォルト値説明

swaggerCodegenMavenPluginVersion

3.0.36

使用する io.swagger.codegen.v3:swagger-codegen-maven-plugin Maven プラグインのバージョン。

modelOutput

 

ターゲット出力パス (デフォルトは ${project.build.directory}/generated-sources/openapi)

modelPackage

io.swagger.client.model

生成されたモデルオブジェクト/クラスに使用するパッケージ

modelNamePrefix

 

モデルクラスと列挙型の接頭辞または接尾辞を設定します。

modelNameSuffix

 

モデルクラスと列挙型の接頭辞または接尾辞を設定します。

modelWithXml

false

生成されたモデル内で XML アノテーションを有効にします (JSON および XML のサポートを提供するライブラリーのみで機能)。

configOptions

 

言語固有のパラメーターのマップを swagger-codegen-maven-plugin に渡します。

3.9.7. camel-restdsl-openapi:generate-yaml

Camel REST DSL OpenApi Maven プラグインの camel-restdsl-openapi:generate-yaml ゴールは、Maven から REST DSL YAML 実装ソースコードを生成するために使用されます。

3.9.7.1. オプション

プラグインは、コマンドラインから設定するか (-D 構文を使用)、<configuration> タグの pom.xml ファイルに定義できる次のオプションをサポートします。

Expand
パラメーターデフォルト値説明

skip

false

コード生成をスキップするには、true に設定します。

filterOperation

 

指定された操作 ID のみを含めるために使用されます。複数の ID はコンマで区切ることができます。ワイルドカードを使用できます。たとえば、find* を使用して、find で始まるすべての操作を含めることができます。

specificationUri

src/spec/openapi.json

OpenApi 仕様の URI は、ファイルシステムパス、HTTP およびクラスパスリソースをサポートします。デフォルトでは、プロジェクトディレクトリー内の src/spec/openapi.json です。JSON と YAML をサポートします。

auth

 

OpenApi 仕様定義をリモートで取得するときに認証ヘッダーを追加します。複数の値をコンマで区切って、name:header の URL エンコード文字列を渡します。

outputDirectory

generated-sources/restdsl-openapi

生成されたソースファイルを配置する場所。デフォルトでは、プロジェクトディレクトリー内の generated-sources/restdsl-openapi

fileName

camel-rest.xml

出力としての XML ファイルの名前。

destinationGenerator

 

宛先エンドポイントをカスタマイズするための org.apache.camel.generator.openapi.DestinationGenerator インターフェイスを実装するクラスの完全修飾クラス名

destinationToSyntax

direct:${operationId}

to uri のデフォルトの to 構文では、direct コンポーネントが使用されます。

 

restConfiguration

true

検出された残りコンポーネントを使用した残り設定の生成を含めるかどうか。

apiContextPath

 

restConfigurationtrue に設定されている場合は、openapi エンドポイントパスを定義します。

clientRequestValidation

false

リクエストの検証を有効にするかどうか。

basePath

 

OpenAPI 仕様で定義されている API ベースパスをオーバーライドします。

requestMappingValues

/**

3.9.8. camel-restdsl-openapi:generate-yaml-with-dto

generate-yaml ゴールとして機能しますが、swagger-codegen-maven-plugin を自動的に実行して OpenApi 仕様から DTO モデルクラスの Java ソースコードを生成することにより、DTO モデルクラスも生成します。

このプラグインは、モデル DTO を生成するために swagger-codegen-maven-plugin を使用するためのデフォルトの優れた努力セットのみをサポートするように範囲が定められ、制限されています。さらなるパワーと柔軟性が必要な場合は、このプラグインではなく、Swagger Codegen Maven プラグイン を直接使用して DTO を生成します。

DTO クラスには、次のような追加の依存関係が必要になる場合があります。

    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.10.1</version>
    </dependency>
    <dependency>
      <groupId>io.swagger.core.v3</groupId>
      <artifactId>swagger-core</artifactId>
      <version>2.2.8</version>
    </dependency>
    <dependency>
      <groupId>org.threeten</groupId>
      <artifactId>threetenbp</artifactId>
      <version>1.6.8</version>
    </dependency>
Copy to Clipboard Toggle word wrap
3.9.8.1. オプション

プラグインは次の 追加 オプションをサポートしています。

Expand
パラメーターデフォルト値説明

swaggerCodegenMavenPluginVersion

3.0.36

使用する io.swagger.codegen.v3:swagger-codegen-maven-plugin Maven プラグインのバージョン。

modelOutput

 

ターゲット出力パス (デフォルトは ${project.build.directory}/generated-sources/openapi)

modelPackage

io.swagger.client.model

生成されたモデルオブジェクト/クラスに使用するパッケージ

modelNamePrefix

 

モデルクラスと列挙型の接頭辞または接尾辞を設定します。

modelNameSuffix

 

モデルクラスと列挙型の接頭辞または接尾辞を設定します。

modelWithXml

false

生成されたモデル内で XML アノテーションを有効にします (JSON および XML のサポートを提供するライブラリーのみで機能)。

configOptions

 

言語固有のパラメーターのマップを swagger-codegen-maven-plugin に渡します。

3.10. FIPS 準拠のサポート

FIPS で検証済み/進行中のモジュール (Modules in Process) 暗号ライブラリーを使用する OpenShift Container Platform クラスターを x86_64 アーキテクチャーにインストールすることができます。

クラスター内の Red Hat Enterprise Linux CoreOS (RHCOS) マシンの場合、この変更は、ユーザーがクラスターのデプロイ中に変更できるクラスターオプションを制御する install-config.yaml ファイル内のオプションのステータスに基づいてマシンをデプロイするときに適用されます。Red Hat Enterprise Linux (RHEL) マシンでは、ワーカーマシンとして使用する予定のマシンにオペレーティングシステムをインストールする場合に FIPS モードを有効にする必要があります。これらの設定方法により、クラスターが FIPS コンプライアンス監査の要件を満たしていることが保証されます。最初のシステム起動前に、FIPS 検証済み/プロセス中のモジュール暗号化パッケージのみが有効になります。

クラスターのオペレーティングシステムを初めて起動する前に FIPS を有効にする必要があるため、クラスターのデプロイ後に FIPS を有効にすることはできません。

3.10.1. OpenShift Container Platform での FIPS 検証

OpenShift Container Platform は、オペレーティングシステムコンポーネントに RHEL および RHCOS 内の特定の FIPS Validated/Modules in Process モジュールを使用します。たとえば、ユーザーが OpenShift Container Platform クラスターおよびコンテナーに対して SSH を実行する場合、それらの接続は適切に暗号化されます。

OpenShift Container Platform コンポーネントは Go で作成され、Red Hat の Golang コンパイラーを使用してビルドされます。クラスターの FIPS モードを有効にすると、暗号署名を必要とするすべての OpenShift Container Platform コンポーネントは RHEL および RHCOS 暗号ライブラリーを呼び出します。

FIPS の詳細は、FIPS モードの属性と制限事項 を参照してください。

OpenShift での Camel Spring Boot のデプロイの詳細は、Camel Spring Boot アプリケーションを OpenShift にデプロイする方法 を参照してください。

サポートされている設定の詳細は、Camel for Spring Boot Supported Configurations を参照してください。

第4章 Maven のローカルでの設定

Maven は、Red Hat build of Apache Camel アプリケーションの開発とプロジェクト管理の一般的な選択肢です。

4.1. Maven 設定の準備

Maven は、Apache の無料のオープンソースビルドツールです。

手順

  1. Maven ダウンロードページ から Maven 3.8.6 以降をダウンロードします。

    ヒント

    正しい Maven および JDK バージョンがインストールされていることを確認するには、コマンドターミナルを開いて次のコマンドを入力します。

    mvn --version
    Copy to Clipboard Toggle word wrap

    出力をチェックして、Maven がバージョン 3.8.6 以降であり、OpenJDK 17 を使用していることを確認します。

  2. システムがインターネットに接続していることを確認します。

    デフォルトの動作では、プロジェクトのビルド中、Maven は外部リポジトリーを検索し、必要なアーティファクトをダウンロードします。Maven はインターネット上でアクセス可能なリポジトリーを探します。

    このデフォルト動作を変更し、Maven によってローカルネットワーク上のリポジトリーのみが検索されるようにすることができます。これは Maven をオフラインモードで実行できることを意味します。オフラインモードでは、Maven によってローカルリポジトリーのアーティファクトが検索されます。「ローカル Maven リポジトリーの使用」 を参照してください。

4.2. Maven への Red Hat リポジトリーの追加

Red Hat Maven リポジトリーにあるアーティファクトにアクセスするには、Red Hat Maven リポジトリーを Maven の settings.xml ファイルに追加する必要があります。

Maven は、ユーザーのホームディレクトリーの .m2 ディレクトリーで settings.xml ファイルを探します。ユーザー指定の settings.xml ファイルがない場合、Maven は M2_HOME/conf/settings.xml にあるシステムレベルの settings.xml ファイルを使用します。

前提条件

Red Hat リポジトリーを追加する settings.xml ファイルがある場所を把握している。

手順

  • 以下の例のように、settings.xml ファイルに Red Hat リポジトリーの repository 要素を追加します。
注記

camel-jira コンポーネントを使用している場合は、atlassian リポジトリーも追加します。

注記

テクノロジープレビューのビルドを使用する必要がある場合は、earlyaccess リポジトリーも追加します。

<?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>atlassian</id>
            <url>https://packages.atlassian.com/artifactory/maven-public/</url>
            <name>atlassian external repo</name>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <releases>
                <enabled>true</enabled>
            </releases>
        </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>
    </profile>
  </profiles>

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

</settings>
Copy to Clipboard Toggle word wrap

4.3. オフライン Maven リポジトリーの構築

Red Hat build of Apache Camel for Spring Boot ユーザーは、制限された環境で使用される独自のオフライン Maven リポジトリーを構築できます。ユーザーは、Red Hat カスタマーポータルから Red Hat build of Apache Camel for Spring Boot の各リリースの zip ファイルをダウンロードできます。

手順

  1. カスタマーポータルから offile Maven リポジトリービルダーをダウンロードします。たとえば、Red Hat build of Camel Spring Boot バージョン 4.10 の場合、オフライン Maven ビルダー を使用します。
  2. ダウンロードしたファイルは、特定のリリース用のオフライン Maven リポジトリーを構築するために必要なものがすべて含まれた zip ファイルです。
  3. ダウンロードした zip ファイルを展開します。アーカイブのディレクトリー構造は次のとおりです。

    ├──build-offline-repo.sh
    ├──logback.xml
    ├──maven-repositories.txt
    ├──offliner-2.2.jar
    ├──offliner-2.2.jar.md5
    ├──offliner-2.2-sources.jar
    ├──offliner-2.2-sources.jar.md5
    ├──README
    ├──rhaf-camel-offliner-4.10.3.txt
    └──rhaf-camel-spring-boot-offliner-4.10.3.txt
    Copy to Clipboard Toggle word wrap

    この zip には次のファイルが含まれています。

    • build-offline-repo.sh - Offliner ツールを囲むラッパースクリプト。
    • offliner-2.0.jar - マニフェスト内のアーティファクトをダウンロードします。
    • redhat-camel-4.8.0-offline-manifest.txt

      • ダウンロードする必要がある必須アーティファクトをリストします。
    • redhat-camel-spring-boot-4.8.0-offline-manifest.txt

      • ダウンロードする必要がある必須アーティファクトをリストします。
    • README - オフライン Maven リポジトリーのビルドに必要な手順とコマンドを説明します。
  4. オフラインリポジトリーをビルドするには、README ファイルに記載されている指示に従って build-offline-repo.sh スクリプトを実行します。オプションで、アーティファクトをダウンロードするディレクトリーを指定できます。指定しない場合は、現在の作業ディレクトリーに 'repository' というディレクトリーが作成されます。

必要に応じて、追加の Maven リポジトリーを使用するようにツールを設定できます。その場合は、maven-repositories.txt ファイルに Maven リポジトリーを追加します。ツールには適切な Maven リポジトリーセットが事前に設定されているため、通常、この操作は必要ありません。

HTTP プロキシーと、このプロキシーを経由する必要がある HTTP 呼び出しの場合は、スクリプトを変更する必要がある場合があります。スクリプト内の JVM を呼び出す行に、引数 --proxy <proxy-host> --proxy-user <proxy-user> --proxy-pass <proxy-pass> を追加します。

オプション -v を使用すると、スクリプトのバージョン番号を出力できます。このバージョンはスクリプトのバージョン番号であり、Red Hat build of Apache Camel の製品バージョンとは関係ありません。

トラブルシューティング

提供されている logback.xml ファイルを使用してロギングを設定できます。シェルスクリプトが実行されると、ダウンロードアクティビティーはすべてログファイル offliner.log に書き込まれ、ダウンロードの失敗はすべて errors.log にリストされます。実行の最後に、offliner ツールによりダウンロードされたアーティファクトと失敗したアーティファクトの概要が表示されますが、さらに errors.log をスキャンしてダウンロードの失敗がないか確認することが推奨されます。

アーティファクトのダウンロードに失敗した場合は、同じターゲットフォルダーに対してツールを再実行します。ツールは、すでにダウンロードしたアーティファクトのダウンロードを回避し、以前に失敗したアーティファクトのみをダウンロードしようとします。

4.4. ローカル Maven リポジトリーの使用

インターネットへ接続せずにコンテナーを実行し、オフライン状態では使用できない依存関係を持つアプリケーションをデプロイする場合は、Maven 依存関係プラグインを使用してアプリケーションの依存関係を Maven オフラインリポジトリーにダウンロードできます。ダウンロード後、このカスタマイズされた Maven オフラインリポジトリーをインターネットに接続していないマシンに提供できます。

手順

  1. pom.xml ファイルが含まれるプロジェクトディレクトリーで、以下のようなコマンドを実行し、Maven プロジェクトのリポジトリーをダウンロードします。

    mvn org.apache.maven.plugins:maven-dependency-plugin:3.1.0:go-offline -Dmaven.repo.local=/tmp/my-project
    Copy to Clipboard Toggle word wrap

    この例では、プロジェクトのビルドに必要な Maven 依存関係とプラグインは /tmp/my-project ディレクトリーにダウンロードされます。

  2. このカスタマイズされた Maven オフラインリポジトリーを、インターネットに接続していない内部のマシンに提供します。

4.5. 環境変数またはシステムプロパティーを使用した Maven ミラーの設定

アプリケーションの実行時に、Red Hat Maven リポジトリーにあるアーティファクトにアクセスする必要があります。このリポジトリーは、Maven の settings.xml ファイルに追加されます。Maven は以下の場所で settings.xml を探します。

  • 指定の URL を検索します。
  • 見つからない場合は ${user.home}/.m2/settings.xml を検索します。
  • 見つからない場合は ${maven.home}/conf/settings.xml を検索します。
  • 見つからない場合は ${M2_HOME}/conf/settings.xml を検索します。
  • どの場所にも見つからない場合は、空の org.apache.maven.settings.Settings インスタンスが作成されます。

4.5.1. Maven ミラー

Maven では、一連のリモートリポジトリーを使用して、ローカルリポジトリーで現在利用できないアーティファクトにアクセスします。ほとんどの場合、リポジトリーのリストには Maven Central リポジトリーが含まれますが、Red Hat Fuse では Maven Red Hat リポジトリーも含まれます。リモートリポジトリーへのアクセスが不可能な場合や許可されない場合は、Maven ミラーのメカニズムを使用できます。ミラーは、特定のリポジトリー URL を異なるリポジトリー URL に置き換えるため、リモートアーティファクトの検索時にすべての HTTP トラフィックを単一の URL に転送できます。

4.5.2. Maven ミラーの settings.xml への追加

Maven ミラーを設定するには、以下のセクションを Maven の settings.xml に追加します。

<mirror>
      <id>all</id>
      <mirrorOf>*</mirrorOf>
      <url>http://host:port/path</url>
</mirror>
Copy to Clipboard Toggle word wrap

settings.xml ファイルに上記のセクションがない場合は、ミラーが使用されません。XML 設定を提供せずにグローバルミラーを指定するには、システムプロパティーまたは環境変数を使用します。

4.5.3. 環境変数またはシステムプロパティーを使用した Maven ミラーの設定

環境変数またはシステムプロパティーのいずれかを使用して Maven ミラーを設定するには、以下を追加します。

  • 環境変数 MAVEN_MIRROR_URLbin/setenv ファイルに追加します。
  • システムプロパティー mavenMirrorUrletc/system.properties ファイルに追加します。

4.5.4. Maven オプションを使用した Maven ミラー URL の指定

環境変数またはシステムプロパティーによって指定された Maven ミラー URL ではなく、別の Maven ミラー URL を使用するには、アプリケーションの実行時に以下の Maven オプションを使用します。

  • -DmavenMirrorUrl=mirrorId::mirrorUrl

    たとえば、-DmavenMirrorUrl=my-mirror::http://mirror.net/repository となります。

  • -DmavenMirrorUrl=mirrorUrl

    たとえば、-DmavenMirrorUrl=http://mirror.net/repository となります。この例では、<mirror> の <id> は mirror になります。

4.6. Maven アーティファクトおよびコーディネート

Maven ビルドシステムでは、アーティファクト が基本的なビルディングブロックです。ビルド後のアーティファクトの出力は、通常 JAR や WAR ファイルなどのアーカイブになります。

Maven の主な特徴として、アーティファクトを検索し、検索したアーティファクト間で依存関係を管理できる機能が挙げられます。Maven コーディネート は、特定のアーティファクトの場所を特定する値のセットです。基本的なコーディネートには、以下の形式の 3 つの値があります。

groupId:artifactId:version

Maven は、packaging の値、または packaging 値と classifier 値の両方を使用して基本的なコーディネートを拡張することがあります。Maven コーディネートには以下の形式のいずれかを使用できます。

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

値の説明は次のとおりです。

groupdId
アーティファクトの名前の範囲を定義します。通常、パッケージ名のすべてまたは一部をグループ ID として使用します。たとえば、org.fusesource.example です。
artifactId
グループ名に関連するアーティファクト名を定義します。
version
アーティファクトのバージョンを指定します。バージョン番号には n.n.n.n のように最大 4 つの部分を使用でき、最後の部分には数字以外の文字を使用できます。たとえば 1.0-SNAPSHOT の場合は、最後の部分が英数字のサブ文字列である 0-SNAPSHOT になります。
packaging
プロジェクトのビルド時に生成されるパッケージ化されたエンティティーを定義します。OSGi プロジェクトでは、パッケージングは bundle になります。デフォルト値は jar です。
classifier
同じ POM からビルドされた内容が異なるアーティファクトを区別できるようにします。

次に示すように、アーティファクトの POM ファイル内の要素で、アーティファクトのグループ ID、アーティファクト ID、パッケージング、およびバージョンを定義します。

<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

前述のアーティファクトの依存関係を定義するには、以下の dependency 要素を POM ファイルに追加します。

<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 要素を使用できます。

第5章 サンプルアプリケーション

5.1. サンプル Spring Boot

Spring Boot examples のリポジトリーには、さまざまなユースケースで Camel と統合する方法の例が多数含まれています。ベストプラクティスのアドバイスを提供し、インテグレーションやメッセージングの問題でよく見られるパターンを説明します。

この例は Maven を使用して実行できます。mvn コマンドを使用すると、Maven は必要な依存関係を中央リポジトリーからローカルリポジトリーにダウンロードしようとします。

5.2. サンプルリポジトリー

61 個の例があります。

Expand
カテゴリー説明devfile でデプロイする

ActiveMQ (activemq)

メッセージング

Camel、ActiveMQ openwire、Spring Boot での使用方法を示す例

いいえ

Actuator HTTP Metrics (actuator-http-metrics)

管理とモニタリング

Spring Boot の Actuator エンドポイントを使用してマッピングやメトリクスなどの情報を収集する方法の例

いいえ

Amqp (amqp)

メッセージング

Camel、ActiveMQ Amqp、Spring Boot での使用方法を示す例

いいえ

AMQP Salesforce (amqp-salesforce)

メッセージング

AMQP メッセージ送信は Salesforce での連絡先として作成されます

いいえ

ArangoDB (arangodb)

データベース

Spring Boot での Camel ArangoDb コンポーネントの使用例

いいえ

artemis (artemis)

メッセージング

Camel、ActiveMQ Artemis、Spring Boot での使用方法を示す例

いいえ

AWS2 S3 (aws2-s3)

クラウド

Spring Boot での Camel AWS2 S3 コンポーネントの使用例

いいえ

Azure Event Hubs (azure-eventhubs)

クラウド

Camel、Azure Event Hubs、Spring Boot での使用方法を示す例

いいえ

Azure Service Bus (azure-servicebus)

クラウド

Camel、Azure Service Bus、Spring Boot での使用方法を示す例

いいえ

Endpoint DSL (camel-example-endpointdsl)

初心者

type-safe Endpoint DSL の使用

いいえ

FHIR (fhir)

ヘルスケア

Camel、FHIR、Spring Boot での使用方法を示す例

いいえ

Transaction (fhir-auth-tx)

ヘルスケア

Camel、FHIR Authorization、FHIR Transaction、Spring Boot での使用方法を示す例

はい

Health Checks (health-checks)

ヘルスケア

Spring Boot を使用したシンプルな Apache Camel アプリケーションでヘルスチェックを操作する方法の例。

はい

HTTP SSL (http-ssl)

Rest

Spring Boot と SSL を使用する Camel HTTP コンポーネントの例

いいえ

Infinispan (infinispan)

クラウド

Spring Boot を使用する Camel Infinispan コンポーネントの例

いいえ

Jira (jira)

初心者

Jira Camel API を使用する例

いいえ

Jolokia (jolokia)

管理とモニタリング

Jolokia を使用して Camel Routes を監視および管理する例

いいえ

Avro (kafka-avro)

メッセージング

Kafka avro の例

いいえ

offsetrepository (kafka-offsetrepository)

メッセージング

Kafka offsetrepository の例

いいえ

Kamelet Chuck Norris (kamelet-chucknorris)

初心者

独自の Kamelets を簡単に作成

はい

Custom Type Converter (load-balancer-eip)

初心者

Camel と Spring Boot を使用するロードバランサー EIP の例

はい

Microsoft Exchange Oauth2 Authentication (mail-exchange-oauth2)

Mail

Spring Boot で Camel を使用して IMAP プロトコルに接続し、OAuth2 認証を使用して Office 365 ユーザーのメールデータにアクセスする方法を示す例

いいえ

Master (master)

クラスタリング

Camel のマスターコンポーネントと Spring Boot の使用方法を示す例

いいえ

Metrics (metrics)

管理とモニタリング

Camel と Spring Boot を操作して Graphite にメトリクスを報告する方法を示す例

はい

Monitoring (monitoring)

管理とモニタリング

Spring Boot の Actuator エンドポイントを使用してマッピングやメトリクスなどの情報を収集する方法の例

いいえ

Multiple pooled datasources with two-phase commit (muti-datasources-2pc)

データベース

2 フェーズコミットでプールされた複数のデータソースを使用して Camel と Spring Boot を操作する方法を示す例

いいえ

Observation (observation)

管理とモニタリング

Micrometer Observation を使用して Camel からの送受信メッセージをトレースする方法を示す例

いいえ

OpenAPI Contract First (openapi-contract-first)

Rest

Contract First OpenAPI の例

いいえ

OpenTelemetry (opentelemetry)

管理とモニタリング

Camel を OpenTelemetry で使用する方法を示す例

いいえ

Paho MQTT5 Shared Subscriptions (paho-mqtt5-shared-subscriptions)

メッセージング

MQTT5 の共有サブスクリプション機能を使用する複数の mqtt5 コンシューマーを設定する方法を示す例

はい

REST DSL and Platform HTTP (platform-http)

Rest

プラットフォーム HTTP を使用する Camel REST DSL の例

いいえ

POJO Routing (pojo)

初心者

Spring Boot で Camel POJO ルーティングを使用する方法を示す例

はい

Quartz (quartz)

初心者

Spring Boot で Camel Quartz と Camel Log を操作する方法を示す例

はい

RabbitMQ (rabbitmq)

メッセージング

Camel と RabbitMQ の操作方法を示す例

いいえ

Reactive Streams (reactive-streams)

リアクティブ

Camel が Spring Boot リアクターとリアクティブストリームを使用してデータを交換する方法を示す例

はい

Resilience4j (resilience4j)

EIP

Camel ルートで Resilience4j EIP をサーキットブレーカーとして使用する方法を示す例

いいえ

REST using CXF and OpenTelemetry (rest-cxf-opentelemetry)

CXF

Spring Boot で CXF と OpenTelemetry を使用する Camel REST の例

いいえ

REST DSL and OpenApi (rest-openapi)

Rest

Spring Boot で Camel REST DSL と OpenApi を使用する例

はい

OpenApi Simple (rest-openapi-simple)

初心者

この例では、OpenApi 仕様を使用して定義された REST サービスを呼び出す方法を示します。

いいえ

REST DSL and OpenApi (rest-openapi-springdoc)

Rest

Spring Boot アプリケーションで Springdoc UI を使用する Camel REST DSL と OpenApi の例

はい

REST DSL と Spring Security (rest-spring-security)

Rest

Spring Boot アプリケーションで Spring Security と JWT トークンを使用して保護された Camel REST DSL を示す例

はい

Route Reload (route-reload)

初心者

ファイルが更新および保存された場合のルートのライブリロード

はい

Routes Configuration (routes-configuration)

初心者

エラー処理のためのグローバルルート設定の例

いいえ

Route Template (routetemplate)

初心者

How to use route templates (parameterized routes)

はい

XML (routetemplate-xml)

初心者

XML でルートテンプレート (パラメーター化されたルート) を使用する方法

いいえ

Saga (saga)

EIP

この例では、Spring Boot と Narayana LRA Coordinator を使用して、SAGA パターンを実装する分散アクションを管理するシンプルな Apache Camel アプリケーションを操作する方法を示します。

いいえ

ServiceCall (servicecall)

クラウド

Camel ServiceCall EIP と Spring Boot の操作方法を示す例

いいえ

SOAP CXF (soap-cxf)

CXF

Camel SOAP CXF の例

いいえ

Camel Splitter EIP (splitter-eip)

初心者

Camel および Spring Boot で Splitter EIP を使用する例

はい

Spring Boot (camel-example-spring-boot)

初心者

Camel および Spring Boot の操作方法を示す例

いいえ

JTA (spring-boot-jta-jpa-autoconfigure)

高度

Spring Boot Autoconfiguration を使用する JTA の例

いいえ

JTA (spring-boot-jta-jpa-xml)

高度

Spring XML 設定を使用する Spring Boot で JTA を使用する例

いいえ

Spring JDBC (spring-jdbc)

初心者

ローカル Spring Transaction を統合する Camel トランザクションルート

いいえ

Strimzi (strimzi)

メッセージング

Openshift/Kubernetes 上の Strimzi 統合用に XML でルートを定義する Camel の例

いいえ

Supervising Route Controller (supervising-route-controller)

管理とモニタリング

Camel の Supervising Route Controller と Spring Boot の操作方法を示す例

はい

Tomcat JDBC (camel-example-spring-boot)

初心者

Tomcat の JDBC データソースを使用して Tomcat に Camel Spring Boot アプリケーションをデプロイする方法を示す例

いいえ

Custom Type Converter (type-converter)

初心者

Camel と Spring Boot を使用してカスタム型コンバーターを作成する方法を示す例

はい

Validator (validator)

入力/出力型のコントラクト

宣言的検証と Spring Boot の操作方法を示す例

はい

webhook: Webhook

高度

Camel Webhook コンポーネントの使用方法の例

いいえ

Widget Gadget (widget-gadget)

メッセージング

Spring Boot で実行する、EIP ブックのウィジェットとガジェットの例

いいえ

XML (xml)

初心者

XML ファイルと Spring Boot で Camel ルートを操作する方法を示す例

はい

XML Import (xml-import)

初心者

埋め込み CamelContext でインポートされた Spring XML ファイルの操作方法を示す例

はい

5.3. サンプルを実行する

サンプルには常に最新リリースを使用する必要があります。

サンプルを実行するには、以下の手順に従います。

  1. 最新リリースのタグを確認します (現在は camel-spring-boot-examples-4.10.7.redhat-00001)。

    $ git checkout tags/camel-spring-boot-examples-4.10.7.redhat-00001

  2. ルート pom をインストールします。

    $ mvn install

  3. 追加の手順は、実行するサンプルの README を確認してください。

5.4. サンプルをデプロイする

devfiles を使用して、OpenShift または dev-sandbox にサンプルをデプロイできます。OpenShift Container Platform での Camel Spring Boot アプリケーションのデプロイに関する詳細は、Apache Camel on OCP Best practices を参照してください。

devfile を使用してデプロイできるのは、一部のサンプルのみです。サンプルが記載された表の "devfile を使用してデプロイ" 列を参照してください。

前提条件

  1. まだの場合は、odo をインストールします (推奨: バージョン 2.x )。

手順

  1. openshift または dev-sandbox にログインし、新しいプロジェクトを作成します。この場合の $EXAMPLE は、デプロイするサンプルの名前です。

    $ oc new-project csbex-$EXAMPLE

  2. devfile.yaml を使用して odo コンポーネントを作成します。

    $ odo create csb-ubi8 --app $EXAMPLE

  3. デプロイするサンプルを環境変数 (SUB_FOLDER) として設定する場合、以下を実行します。

    $ odo config set --env SUB_FOLDER=$EXAMPLE

  4. それを openshift クラスターにプッシュします。

    $ odo push

  5. サンプルをデプロイする前に、リポジトリー内の .odo ディレクトリーを削除します。

    これにより、前に使用したサンプルに関連するコンポーネントが削除されます。

  6. 内部リポジトリーがある場合は、プッシュする前に Maven リポジトリーで MAVEN_MIRROR_URL 環境を設定します。

    $ odo config set --env MAVEN_MIRROR_URL=https://my-maven-mirror/

第6章 Camel Spring Boot インテグレーションのモニタリング

この章では、実行時に Red Hat build of Camel Spring Boot のインテグレーションを監視する方法を説明します。OpenShift Monitoring の一部としてすでにデプロイされている Prometheus Operator を使用して、独自のアプリケーションを監視することができます。

OpenShift Container Platform での Camel Spring Boot アプリケーションのデプロイに関する詳細は、Apache Camel on OCP Best practices を参照してください。

HawtIO 診断コンソールの詳細は、HawtIO 診断コンソールのドキュメント を参照してください。

6.1. OpenShift でのユーザーワークロードモニタリングの有効化

ユーザー定義プロジェクトのモニタリングを有効にするには、クラスターモニタリング ConfigMap オブジェクトの enableUserWorkload: true フィールドを設定します。

重要

OpenShift Container Platform 4.13 では、ユーザー定義プロジェクトのモニタリングを有効にする前に、カスタム Prometheus インスタンスを削除する必要があります。

前提条件

OpenShift Container Platform のユーザー定義プロジェクトのモニタリングを有効にするには、cluster-admin クラスターロールアクセスを持つユーザーとしてクラスターにアクセスできる必要があります。これにより、クラスター管理者は任意で、ユーザー定義のプロジェクトをモニターするコンポーネントを設定する権限をユーザーに付与できます。

  • OpenShift クラスターにアクセス可能な cluster admin 権限がある。
  • OpenShift CLI (oc) がインストールされている。
注記

設定の変更を user-workload-monitoring-config ConfigMap に保存するたびに、openshift-user-workload-monitoring プロジェクトの Pod が再デプロイされます。これらのコンポーネントが再デプロイするまで時間がかかる場合があります。ユーザー定義プロジェクトのモニタリングを最初に有効にする前に ConfigMap オブジェクトを作成し、設定することができます。これにより、Pod を頻繁に再デプロイする必要がなくなります。

手順

  1. 管理者権限で OpenShift にログインします。

    oc login --user system:admin --token=my-token --server=https://my-cluster.example.com:6443
    Copy to Clipboard Toggle word wrap
  2. cluster-monitoring-config ConfigMap オブジェクトを編集します。

    $ oc -n openshift-monitoring edit configmap cluster-monitoring-config
    Copy to Clipboard Toggle word wrap
  3. data/config.yaml セクションに enableUserWorkload: true を追加します。

        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: cluster-monitoring-config
          namespace: openshift-monitoring
        data:
          config.yaml: |
            enableUserWorkload: true
    Copy to Clipboard Toggle word wrap

    true に設定すると、enableUserWorkload パラメーターはクラスター内のユーザー定義プロジェクトのモニタリングを有効にします。

  4. 変更を適用するためにファイルを保存します。ユーザー定義プロジェクトのモニタリングは自動的に有効になります。

    注記

    変更が cluster-monitoring-config ConfigMap オブジェクトに保存されると、openshift-monitoring プロジェクトの Pod および他のリソースは再デプロイされる可能性があります。該当するプロジェクトの実行中のモニタリングプロセスも再起動する可能性があります。

  5. prometheus-operatorprometheus-user-workload および thanos-ruler-user-workload Pod が openshift-user-workload-monitoring プロジェクトで実行中であることを確認します。

    $ oc -n openshift-user-workload-monitoring get pod
    
        Example output
    
        NAME                                   READY   STATUS        RESTARTS   AGE
        prometheus-operator-6f7b748d5b-t7nbg   2/2     Running       0          3h
        prometheus-user-workload-0             4/4     Running       1          3h
        prometheus-user-workload-1             4/4     Running       1          3h
        thanos-ruler-user-workload-0           3/3     Running       0          3h
        thanos-ruler-user-workload-1           3/3     Running       0          3h
    Copy to Clipboard Toggle word wrap

6.2. Camel Spring Boot アプリケーションのモニタリング

プロジェクトのモニタリングを有効にすると、Camel Spring Boot アプリケーションをデプロイして監視できるようになります。このセクションでは、Camel Spring Boot Examples にリスト表示されている monitoring-micrometrics-grafana-prometheus の例を使用します。

手順

  1. openshift-maven-plugin を、monitoring-micrometrics-grafana-prometheus サンプルの pom.xml ファイルに追加します。pom.xmlopenshift プロファイルを追加して、openshift-maven-plugin を介して openshift にデプロイできるようにします。
  2. openshift-maven-plugin を、monitoring-micrometrics-grafana-prometheus サンプルの pom.xml ファイルに追加します。pom.xmlopenshift プロファイルを追加して、openshift-maven-plugin を使用して openshift にデプロイできるようにします。

        <profiles>
            <profile>
                <id>openshift</id>
                <build>
                    <plugins>
                        <plugin>
                            <groupId>org.eclipse.jkube</groupId>
                            <artifactId>openshift-maven-plugin</artifactId>
                            <version>1.13.1</version>
                            <executions>
                                <execution>
                                    <goals>
                                        <goal>resource</goal>
                                        <goal>build</goal>
                                    </goals>
                                </execution>
                            </executions>
                        </plugin>
                    </plugins>
                </build>
            </profile>
        </profiles>
    Copy to Clipboard Toggle word wrap
  3. Prometheus サポートを追加します。Camel アプリケーションに Prometheus サポートを追加するには、アクチュエーターエンドポイントで Prometheus 統計情報を公開します。

    1. src/main/resources/application.properties ファイルを編集します。
    2. management.endpoints.web.exposure.include エントリーが存在しない場合は追加します。
    3. management.endpoints.web.exposure.include エントリーに prometheus、metrics、health を追加します。

      # expose actuator endpoint via HTTP
      management.endpoints.web.exposure.include=mappings,metrics,health,shutdown,jolokia,prometheus
      Copy to Clipboard Toggle word wrap
  4. pom.xml の <dependencies/> セクションに以下を追加して、アプリケーションにスターターサポートを追加します。

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>6.1.8</version>
    </dependency>
    
    <dependency>
        <groupId>io.micrometer</groupId>
        <artifactId>micrometer-registry-prometheus</artifactId>
        <version>1.13.6</version>
    </dependency>
    
    <dependency>
        <groupId>org.jolokia</groupId>
        <artifactId>jolokia-server-core</artifactId>
        <version>2.2.5.redhat-00001</version>
    </dependency>
    
    <dependency>
        <groupId>io.prometheus.jmx</groupId>
        <artifactId>collector</artifactId>
        <version>1.0.1</version>
    </dependency>
    Copy to Clipboard Toggle word wrap
  5. ファイル config/prometheus_exporter_config.yml を作成します。

    startDelaySecs: 5
    ssl: false
    blacklistObjectNames: ["java.lang:*"]
    rules:
      # Context level
      - pattern: 'org.apache.camel<context=([^,]+), type=context, name=([^,]+)><>ExchangesCompleted'
        name: org.apache.camel.ExchangesCompleted
        help: Exchanges Completed
        type: COUNTER
        labels:
          context: $1
          type: context
      - pattern: 'org.apache.camel<context=([^,]+), type=context, name=([^,]+)><>ExchangesFailed'
        name: org.apache.camel.ExchangesFailed
        help: Exchanges Failed
        type: COUNTER
        labels:
          context: $1
          type: context
      - pattern: 'org.apache.camel<context=([^,]+), type=context, name=([^,]+)><>ExchangesInflight'
        name: org.apache.camel.ExchangesInflight
        help: Exchanges Inflight
        type: GAUGE
        labels:
          context: $1
          type: context
      - pattern: 'org.apache.camel<context=([^,]+), type=context, name=([^,]+)><>ExchangesTotal'
        name: org.apache.camel.ExchangesTotal
        help: Exchanges Total
        type: COUNTER
        labels:
          context: $1
          type: context
      - pattern: 'org.apache.camel<context=([^,]+), type=context, name=([^,]+)><>FailuresHandled'
        name: org.apache.camel.FailuresHandled
        help: Failures Handled
        labels:
          context: $1
          type: context
        type: COUNTER
      - pattern: 'org.apache.camel<context=([^,]+), type=context, name=([^,]+)><>ExternalRedeliveries'
        name: org.apache.camel.ExternalRedeliveries
        help: External Redeliveries
        labels:
          context: $1
          type: context
        type: COUNTER
      - pattern: 'org.apache.camel<context=([^,]+), type=context, name=([^,]+)><>MaxProcessingTime'
        name: org.apache.camel.MaxProcessingTime
        help: Maximum Processing Time
        labels:
          context: $1
          type: context
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=context, name=([^,]+)><>MeanProcessingTime'
        name: org.apache.camel.MeanProcessingTime
        help: Mean Processing Time
        labels:
          context: $1
          type: context
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=context, name=([^,]+)><>MinProcessingTime'
        name: org.apache.camel.MinProcessingTime
        help: Minimum Processing Time
        labels:
          context: $1
          type: context
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=context, name=([^,]+)><>LastProcessingTime'
        name: org.apache.camel.LastProcessingTime
        help: Last Processing Time
        labels:
          context: $1
          type: context
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=context, name=([^,]+)><>DeltaProcessingTime'
        name: org.apache.camel.DeltaProcessingTime
        help: Delta Processing Time
        labels:
          context: $1
          type: context
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=context, name=([^,]+)><>Redeliveries'
        name: org.apache.camel.Redeliveries
        help: Redeliveries
        labels:
          context: $1
          type: context
        type: COUNTER
      - pattern: 'org.apache.camel<context=([^,]+), type=context, name=([^,]+)><>TotalProcessingTime'
        name: org.apache.camel.TotalProcessingTime
        help: Total Processing Time
        labels:
          context: $1
          type: context
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=consumers, name=([^,]+)><>InflightExchanges'
        name: org.apache.camel.InflightExchanges
        help: Inflight Exchanges
        labels:
          context: $1
          type: context
        type: GAUGE
    
      # Route level
      - pattern: 'org.apache.camel<context=([^,]+), type=routes, name=([^,]+)><>ExchangesCompleted'
        name: org.apache.camel.ExchangesCompleted
        help: Exchanges Completed
        type: COUNTER
        labels:
          context: $1
          route: $2
          type: routes
      - pattern: 'org.apache.camel<context=([^,]+), type=routes, name=([^,]+)><>ExchangesFailed'
        name: org.apache.camel.ExchangesFailed
        help: Exchanges Failed
        type: COUNTER
        labels:
          context: $1
          route: $2
          type: routes
      - pattern: 'org.apache.camel<context=([^,]+), type=routes, name=([^,]+)><>ExchangesInflight'
        name: org.apache.camel.ExchangesInflight
        help: Exchanges Inflight
        type: GAUGE
        labels:
          context: $1
          route: $2
          type: routes
      - pattern: 'org.apache.camel<context=([^,]+), type=routes, name=([^,]+)><>ExchangesTotal'
        name: org.apache.camel.ExchangesTotal
        help: Exchanges Total
        type: COUNTER
        labels:
          context: $1
          route: $2
          type: routes
      - pattern: 'org.apache.camel<context=([^,]+), type=routes, name=([^,]+)><>FailuresHandled'
        name: org.apache.camel.FailuresHandled
        help: Failures Handled
        labels:
          context: $1
          route: $2
          type: routes
        type: COUNTER
      - pattern: 'org.apache.camel<context=([^,]+), type=routes, name=([^,]+)><>ExternalRedeliveries'
        name: org.apache.camel.ExternalRedeliveries
        help: External Redeliveries
        labels:
          context: $1
          route: $2
          type: routes
        type: COUNTER
      - pattern: 'org.apache.camel<context=([^,]+), type=routes, name=([^,]+)><>MaxProcessingTime'
        name: org.apache.camel.MaxProcessingTime
        help: Maximum Processing Time
        labels:
          context: $1
          route: $2
          type: routes
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=routes, name=([^,]+)><>MeanProcessingTime'
        name: org.apache.camel.MeanProcessingTime
        help: Mean Processing Time
        labels:
          context: $1
          route: $2
          type: routes
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=routes, name=([^,]+)><>MinProcessingTime'
        name: org.apache.camel.MinProcessingTime
        help: Minimum Processing Time
        labels:
          context: $1
          route: $2
          type: routes
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=routes, name=([^,]+)><>LastProcessingTime'
        name: org.apache.camel.LastProcessingTime
        help: Last Processing Time
        labels:
          context: $1
          route: $2
          type: routes
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=routes, name=([^,]+)><>DeltaProcessingTime'
        name: org.apache.camel.DeltaProcessingTime
        help: Delta Processing Time
        labels:
          context: $1
          route: $2
          type: routes
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=routes, name=([^,]+)><>Redeliveries'
        name: org.apache.camel.Redeliveries
        help: Redeliveries
        labels:
          context: $1
          route: $2
          type: routes
        type: COUNTER
      - pattern: 'org.apache.camel<context=([^,]+), type=routes, name=([^,]+)><>TotalProcessingTime'
        name: org.apache.camel.TotalProcessingTime
        help: Total Processing Time
        labels:
          context: $1
          route: $2
          type: routes
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=routes, name=([^,]+)><>InflightExchanges'
        name: org.apache.camel.InflightExchanges
        help: Inflight Exchanges
        labels:
          context: $1
          route: $2
          type: routes
        type: GAUGE
    
      # Processor level
      - pattern: 'org.apache.camel<context=([^,]+), type=processors, name=([^,]+)><>ExchangesCompleted'
        name: org.apache.camel.ExchangesCompleted
        help: Exchanges Completed
        type: COUNTER
        labels:
          context: $1
          processor: $2
          type: processors
      - pattern: 'org.apache.camel<context=([^,]+), type=processors, name=([^,]+)><>ExchangesFailed'
        name: org.apache.camel.ExchangesFailed
        help: Exchanges Failed
        type: COUNTER
        labels:
          context: $1
          processor: $2
          type: processors
      - pattern: 'org.apache.camel<context=([^,]+), type=processors, name=([^,]+)><>ExchangesInflight'
        name: org.apache.camel.ExchangesInflight
        help: Exchanges Inflight
        type: GAUGE
        labels:
          context: $1
          processor: $2
          type: processors
      - pattern: 'org.apache.camel<context=([^,]+), type=processors, name=([^,]+)><>ExchangesTotal'
        name: org.apache.camel.ExchangesTotal
        help: Exchanges Total
        type: COUNTER
        labels:
          context: $1
          processor: $2
          type: processors
      - pattern: 'org.apache.camel<context=([^,]+), type=processors, name=([^,]+)><>FailuresHandled'
        name: org.apache.camel.FailuresHandled
        help: Failures Handled
        labels:
          context: $1
          processor: $2
          type: processors
        type: COUNTER
      - pattern: 'org.apache.camel<context=([^,]+), type=processors, name=([^,]+)><>ExternalRedeliveries'
        name: org.apache.camel.ExternalRedeliveries
        help: External Redeliveries
        labels:
          context: $1
          processor: $2
          type: processors
        type: COUNTER
      - pattern: 'org.apache.camel<context=([^,]+), type=processors, name=([^,]+)><>MaxProcessingTime'
        name: org.apache.camel.MaxProcessingTime
        help: Maximum Processing Time
        labels:
          context: $1
          processor: $2
          type: processors
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=processors, name=([^,]+)><>MeanProcessingTime'
        name: org.apache.camel.MeanProcessingTime
        help: Mean Processing Time
        labels:
          context: $1
          processor: $2
          type: processors
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=processors, name=([^,]+)><>MinProcessingTime'
        name: org.apache.camel.MinProcessingTime
        help: Minimum Processing Time
        labels:
          context: $1
          processor: $2
          type: processors
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=processors, name=([^,]+)><>LastProcessingTime'
        name: org.apache.camel.LastProcessingTime
        help: Last Processing Time
        labels:
          context: $1
          processor: $2
          type: processors
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=processors, name=([^,]+)><>DeltaProcessingTime'
        name: org.apache.camel.DeltaProcessingTime
        help: Delta Processing Time
        labels:
          context: $1
          processor: $2
          type: processors
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=processors, name=([^,]+)><>Redeliveries'
        name: org.apache.camel.Redeliveries
        help: Redeliveries
        labels:
          context: $1
          processor: $2
          type: processors
        type: COUNTER
      - pattern: 'org.apache.camel<context=([^,]+), type=processors, name=([^,]+)><>TotalProcessingTime'
        name: org.apache.camel.TotalProcessingTime
        help: Total Processing Time
        labels:
          context: $1
          processor: $2
          type: processors
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=processors, name=([^,]+)><>InflightExchanges'
        name: org.apache.camel.InflightExchanges
        help: Inflight Exchanges
        labels:
          context: $1
          processor: $2
          type: processors
        type: COUNTER
    
      # Consumers
      - pattern: 'org.apache.camel<context=([^,]+), type=consumers, name=([^,]+)><>InflightExchanges'
        name: org.apache.camel.InflightExchanges
        help: Inflight Exchanges
        labels:
          context: $1
          consumer: $2
          type: consumers
        type: GAUGE
    
      # Services
      - pattern: 'org.apache.camel<context=([^,]+), type=services, name=([^,]+)><>MaxDuration'
        name: org.apache.camel.MaxDuration
        help: Maximum Duration
        labels:
          context: $1
          service: $2
          type: services
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=services, name=([^,]+)><>MeanDuration'
        name: org.apache.camel.MeanDuration
        help: Mean Duration
        labels:
          context: $1
          service: $2
          type: services
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=services, name=([^,]+)><>MinDuration'
        name: org.apache.camel.MinDuration
        help: Minimum Duration
        labels:
          context: $1
          service: $2
          type: services
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=services, name=([^,]+)><>TotalDuration'
        name: org.apache.camel.TotalDuration
        help: Total Duration
        labels:
          context: $1
          service: $2
          type: services
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=services, name=([^,]+)><>ThreadsBlocked'
        name: org.apache.camel.ThreadsBlocked
        help: Threads Blocked
        labels:
          context: $1
          service: $2
          type: services
        type: GAUGE
      - pattern: 'org.apache.camel<context=([^,]+), type=services, name=([^,]+)><>ThreadsInterrupted'
        name: org.apache.camel.ThreadsInterrupted
        help: Threads Interrupted
        labels:
          context: $1
          service: $2
          type: services
        type: GAUGE
      - pattern: 'org.apache.cxf<bus.id=([^,]+), type=([^,]+), service=([^,]+), port=([^,]+), operation=([^,]+)><>NumLogicalRuntimeFaults'
        name: org.apache.cxf.NumLogicalRuntimeFaults
        help: Number of logical runtime faults
        type: GAUGE
        labels:
          bus.id: $1
          type: $2
          service: $3
          port: $4
          operation: $5
      - pattern: 'org.apache.cxf<bus.id=([^,]+), type=([^,]+), service=([^,]+), port=([^,]+)><>NumLogicalRuntimeFaults'
        name: org.apache.cxf.NumLogicalRuntimeFaults
        help: Number of logical runtime faults
        type: GAUGE
        labels:
          bus.id: $1
          type: $2
          service: $3
          port: $4
      - pattern: 'org.apache.cxf<bus.id=([^,]+), type=([^,]+), service=([^,]+), port=([^,]+), operation=([^,]+)><>AvgResponseTime'
        name: org.apache.cxf.AvgResponseTime
        help: Average Response Time
        type: GAUGE
        labels:
          bus.id: $1
          type: $2
          service: $3
          port: $4
          operation: $5
      - pattern: 'org.apache.cxf<bus.id=([^,]+), type=([^,]+), service=([^,]+), port=([^,]+)><>AvgResponseTime'
        name: org.apache.cxf.AvgResponseTime
        help: Average Response Time
        type: GAUGE
        labels:
          bus.id: $1
          type: $2
          service: $3
          port: $4
      - pattern: 'org.apache.cxf<bus.id=([^,]+), type=([^,]+), service=([^,]+), port=([^,]+), operation=([^,]+)><>NumInvocations'
        name: org.apache.cxf.NumInvocations
        help: Number of invocations
        type: GAUGE
        labels:
          bus.id: $1
          type: $2
          service: $3
          port: $4
          operation: $5
      - pattern: 'org.apache.cxf<bus.id=([^,]+), type=([^,]+), service=([^,]+), port=([^,]+)><>NumInvocations'
        name: org.apache.cxf.NumInvocations
        help: Number of invocations
        type: GAUGE
        labels:
          bus.id: $1
          type: $2
          service: $3
          port: $4
      - pattern: 'org.apache.cxf<bus.id=([^,]+), type=([^,]+), service=([^,]+), port=([^,]+), operation=([^,]+)><>MaxResponseTime'
        name: org.apache.cxf.MaxResponseTime
        help: Maximum Response Time
        type: GAUGE
        labels:
          bus.id: $1
          type: $2
          service: $3
          port: $4
          operation: $5
      - pattern: 'org.apache.cxf<bus.id=([^,]+), type=([^,]+), service=([^,]+), port=([^,]+)><>MaxResponseTime'
        name: org.apache.cxf.MaxResponseTime
        help: Maximum Response Time
        type: GAUGE
        labels:
          bus.id: $1
          type: $2
          service: $3
          port: $4
      - pattern: 'org.apache.cxf<bus.id=([^,]+), type=([^,]+), service=([^,]+), port=([^,]+), operation=([^,]+)><>MinResponseTime'
        name: org.apache.cxf.MinResponseTime
        help: Minimum Response Time
        type: GAUGE
        labels:
          bus.id: $1
          type: $2
          service: $3
          port: $4
          operation: $5
      - pattern: 'org.apache.cxf<bus.id=([^,]+), type=([^,]+), service=([^,]+), port=([^,]+), operation=([^,]+)><>MinResponseTime'
        name: org.apache.cxf.MinResponseTime
        help: Minimum Response Time
        type: GAUGE
        labels:
          bus.id: $1
          type: $2
          service: $3
          port: $4
      - pattern: 'org.apache.cxf<bus.id=([^,]+), type=([^,]+), service=([^,]+), port=([^,]+), operation=([^,]+)><>TotalHandlingTime'
        name: org.apache.cxf.TotalHandlingTime
        help: Total Handling Time
        type: GAUGE
        labels:
          bus.id: $1
          type: $2
          service: $3
          port: $4
          operation: $5
      - pattern: 'org.apache.cxf<bus.id=([^,]+), type=([^,]+), service=([^,]+), port=([^,]+)><>TotalHandlingTime'
        name: org.apache.cxf.TotalHandlingTime
        help: Total Handling Time
        type: GAUGE
        labels:
          bus.id: $1
          type: $2
          service: $3
          port: $4
      - pattern: 'org.apache.cxf<bus.id=([^,]+), type=([^,]+), service=([^,]+), port=([^,]+), operation=([^,]+)><>NumRuntimeFaults'
        name: org.apache.cxf.NumRuntimeFaults
        help: Number of runtime faults
        type: GAUGE
        labels:
          bus.id: $1
          type: $2
          service: $3
          port: $4
          operation: $5
      - pattern: 'org.apache.cxf<bus.id=([^,]+), type=([^,]+), service=([^,]+), port=([^,]+)><>NumRuntimeFaults'
        name: org.apache.cxf.NumRuntimeFaults
        help: Number of runtime faults
        type: GAUGE
        labels:
          bus.id: $1
          type: $2
          service: $3
          port: $4
      - pattern: 'org.apache.cxf<bus.id=([^,]+), type=([^,]+), service=([^,]+), port=([^,]+), operation=([^,]+)><>NumUnCheckedApplicationFaults'
        name: org.apache.cxf.NumUnCheckedApplicationFaults
        help: Number of unchecked application faults
        type: GAUGE
        labels:
          bus.id: $1
          type: $2
          service: $3
          port: $4
          operation: $5
      - pattern: 'org.apache.cxf<bus.id=([^,]+), type=([^,]+), service=([^,]+), port=([^,]+)><>NumUnCheckedApplicationFaults'
        name: org.apache.cxf.NumUnCheckedApplicationFaults
        help: Number of unchecked application faults
        type: GAUGE
        labels:
          bus.id: $1
          type: $2
          service: $3
          port: $4
      - pattern: 'org.apache.cxf<bus.id=([^,]+), type=([^,]+), service=([^,]+), port=([^,]+), operation=([^,]+)><>NumCheckedApplicationFaults'
        name: org.apache.cxf.NumCheckedApplicationFaults
        help: Number of checked application faults
        type: GAUGE
        labels:
          bus.id: $1
          type: $2
          service: $3
          port: $4
          operation: $5
      - pattern: 'org.apache.cxf<bus.id=([^,]+), type=([^,]+), service=([^,]+), port=([^,]+)><>NumCheckedApplicationFaults'
        name: org.apache.cxf.NumCheckedApplicationFaults
        help: Number of checked application faults
        type: GAUGE
        labels:
          bus.id: $1
          type: $2
          service: $3
          port: $4
    Copy to Clipboard Toggle word wrap
  6. Camel アプリケーションの Application.java に以下を追加します。

    import java.io.InputStream;
    import io.micrometer.core.instrument.Clock;
    import org.apache.camel.CamelContext;
    import org.apache.camel.spring.boot.CamelContextConfiguration;
    
    import org.springframework.context.annotation.Bean;
    import org.apache.camel.component.micrometer.MicrometerConstants;
    import org.apache.camel.component.micrometer.eventnotifier.MicrometerExchangeEventNotifier;
    import org.apache.camel.component.micrometer.eventnotifier.MicrometerRouteEventNotifier;
    import org.apache.camel.component.micrometer.messagehistory.MicrometerMessageHistoryFactory;
    import org.apache.camel.component.micrometer.routepolicy.MicrometerRoutePolicyFactory;
    Copy to Clipboard Toggle word wrap
  7. 更新された Application.java を以下に示します。

    @SpringBootApplication
    public class SampleCamelApplication {
    
    @Bean(name = {MicrometerConstants.METRICS_REGISTRY_NAME, "prometheusMeterRegistry"})
    public PrometheusMeterRegistry prometheusMeterRegistry(
            PrometheusConfig prometheusConfig, CollectorRegistry collectorRegistry, Clock clock) throws MalformedObjectNameException, IOException {
    
        InputStream resource = new ClassPathResource("config/prometheus_exporter_config.yml").getInputStream();
    
        new JmxCollector(resource).register(collectorRegistry);
        new BuildInfoCollector().register(collectorRegistry);
        return new PrometheusMeterRegistry(prometheusConfig, collectorRegistry, clock);
    }
    
    @Bean
    public CamelContextConfiguration camelContextConfiguration(@Autowired PrometheusMeterRegistry registry) {
    
        return new CamelContextConfiguration() {
            @Override
            public void beforeApplicationStart(CamelContext camelContext) {
                MicrometerRoutePolicyFactory micrometerRoutePolicyFactory = new MicrometerRoutePolicyFactory();
                micrometerRoutePolicyFactory.setMeterRegistry(registry);
                camelContext.addRoutePolicyFactory(micrometerRoutePolicyFactory);
    
                MicrometerMessageHistoryFactory micrometerMessageHistoryFactory = new MicrometerMessageHistoryFactory();
                micrometerMessageHistoryFactory.setMeterRegistry(registry);
                camelContext.setMessageHistoryFactory(micrometerMessageHistoryFactory);
    
                MicrometerExchangeEventNotifier micrometerExchangeEventNotifier =  new MicrometerExchangeEventNotifier();
                micrometerExchangeEventNotifier.setMeterRegistry(registry);
                camelContext.getManagementStrategy().addEventNotifier(micrometerExchangeEventNotifier);
    
                MicrometerRouteEventNotifier micrometerRouteEventNotifier = new MicrometerRouteEventNotifier();
                micrometerRouteEventNotifier.setMeterRegistry(registry);
                camelContext.getManagementStrategy().addEventNotifier(micrometerRouteEventNotifier);
    
            }
    
            @Override
            public void afterApplicationStart(CamelContext camelContext) {
            }
        };
    }
    Copy to Clipboard Toggle word wrap
  8. アプリケーションを OpenShift にデプロイします。

    mvn -Popenshift oc:deploy
    Copy to Clipboard Toggle word wrap
  9. アプリケーションがデプロイされているかを確認します。

    oc get pods -n myapp
    
    NAME                                        READY   STATUS      RESTARTS   AGE
    camel-example-spring-boot-xml-2-deploy      0/1     Completed   0          13m
    camel-example-spring-boot-xml-2-x78rk       1/1     Running     0          13m
    camel-example-spring-boot-xml-s2i-2-build   0/1     Completed   0          14m
    Copy to Clipboard Toggle word wrap
  10. このアプリケーションのサービスモニターを追加して、Openshift の Prometheus インスタンスが / actuator/prometheus エンドポイントからスクレイピングを開始できるようにします。

    1. サービスモニター用に次の YAML マニフェストを作成します。この例では、ファイルの名前は servicemonitor.yaml です。

      apiVersion: monitoring.coreos.com/v1
      kind: ServiceMonitor
      metadata:
        labels:
          k8s-app: csb-demo-monitor
        name: csb-demo-monitor
      spec:
        endpoints:
        - interval: 30s
          port: http
          scheme: http
          path: /actuator/prometheus
        selector:
          matchLabels:
            app: camel-example-spring-boot-xml
      Copy to Clipboard Toggle word wrap
    2. このアプリケーションのサービスモニターを追加します。

      oc apply -f servicemonitor.yml
      servicemonitor.monitoring.coreos.com/csb-demo-monitor "myapp" created
      Copy to Clipboard Toggle word wrap
  11. サービスモニターが正常にデプロイされたことを確認します。

    oc get servicemonitor
    
    NAME                   AGE
    csb-demo-monitor       9m17s
    Copy to Clipboard Toggle word wrap
  12. スクレイプターゲットのリストにサービスモニターが表示されていることを確認します。Administrator ビューで、Observe → Targets に移動します。csb-demo-monitor は、スクレイプターゲットのリスト内にあります。
  13. servicemonitor をデプロイした後、約 10 分間待ちます。次に、Developer ビューで Observe → Metrics に移動します。ドロップダウンメニューで Custom query を選択し、camel と入力して、/actuator/prometheus エンドポイントを介して公開される Camel メトリクスを表示します。
注記

Red Hat は、OCP 以外の環境での Prometheus と Grafana のインストールおよび設定はサポートしません。

第7章 Spring XML での Camel の使用

Spring XML ファイルで Camel を使用して、Camel で XML DSL を使用できます。Camel は歴史的に長い間 Spring XML を使用してきました。Spring フレームワークは、Spring アプリケーションを構築するための一般的な設定として XML ファイルから始まりました。

Spring アプリケーションの例

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
    ">

    <camelContext xmlns="http://camel.apache.org/schema/spring">
        <route>
            <from uri="direct:a"/>
            <choice>
                <when>
                    <xpath>$foo = 'bar'</xpath>
                    <to uri="direct:b"/>
                </when>
                <when>
                    <xpath>$foo = 'cheese'</xpath>
                    <to uri="direct:c"/>
                </when>
                <otherwise>
                    <to uri="direct:d"/>
                </otherwise>
            </choice>
        </route>
    </camelContext>

</beans>
Copy to Clipboard Toggle word wrap

7.1. Spring XML ファイルでの Java DSL の使用

Java コードを使用して RouteBuilder 実装を定義できます。これらは Spring で Bean として定義され、次に示すように Camel コンテキストで参照されます。

<camelContext xmlns="http://camel.apache.org/schema/spring">
  <routeBuilder ref="myBuilder"/>
</camelContext>

<bean id="myBuilder" class="org.apache.camel.spring.example.test1.MyRouteBuilder"/>
Copy to Clipboard Toggle word wrap

7.1.1. Spring Boot アプリケーションの設定

Spring Boot Autoconfigure XML ルートを Bean で使用するには、XML リソースをインポートを必要とします。これを行うには、Configuration クラスを使用します。

たとえば、Spring XML ファイルが src/main/resources/camel-context.xml にある場合は、以下の設定クラスを使用して camel-context をロードすることができます。

例: Configuration クラスの使用

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;


/**
 * A Configuration class that import the Spring XML resource
 */
@Configuration
// load the spring xml file from classpath
@ImportResource("classpath:camel-context.xml")
public class CamelSpringXMLConfiguration {
}
Copy to Clipboard Toggle word wrap

ヒント

サンプルアプリケーションは、camel-spring-boot-examples リポジトリーの XML import の例を参照してください。

7.2. Spring XML を使用した Camel ルートの指定

次に示すように、Spring XML ファイルを使用して、XML DSL を使用して Camel ルートを指定できます。

<camelContext id="camel-A" xmlns="http://camel.apache.org/schema/spring">
  <route>
    <from uri="seda:start"/>
    <to uri="mock:result"/>
  </route>
</camelContext>
Copy to Clipboard Toggle word wrap

7.3. コンポーネントとエンドポイントの設定

この例の次のように、Spring XML で Component または Endpoint インスタンスを設定できます。

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

<bean id="jmsConnectionFactory" class="org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory">
  <property name="brokerURL" value="tcp:someserver:61616"/>
</bean>
<bean id="jms" class="org.apache.camel.component.jms.JmsComponent">
  <property name="connectionFactory">
    <bean class="org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory">
  <property name="brokerURL" value="tcp:someserver:61616"/>
      </bean>
  </property>
</bean>
Copy to Clipboard Toggle word wrap

これにより、任意の名前を使用してコンポーネントを設定できますが、同じ名前 (jms など) を使用するのが一般的です。その後、jms:destinationName を使用してコンポーネントを参照できます。

これは、Camel がエンドポイント URI に使用するスキーム名の Spring コンテキストからコンポーネントを取得することによって機能します。

7.4. パッケージスキャンの使用

Camel は、特定のパッケージ内のルートの自動検出と初期化を可能にする強力な機能も提供します。これは、Spring コンテキスト定義の Camel コンテキストにタグを追加し、RouteBuilder 実装を再帰的に検索するパッケージを指定することで設定されます。この機能を使用するには、検索するパッケージのコンマ区切りリストを指定する <package></package> タグを追加します。以下に例を示します。

<camelContext>
  <packageScan>
    <package>com.foo</package>
    <excludes>**.*Excluded*</excludes>
    <includes>**.*</includes>
  </packageScan>
</camelContext>
Copy to Clipboard Toggle word wrap

これにより、com.foo およびサブパッケージ内の RouteBuilder クラスがスキャンされます。

次のような包含または除外を使用してクラスをフィルタリングすることもできます。

<camelContext>
  <packageScan>
    <package>com.foo</package>
    <excludes>**.*Special*</excludes>
  </packageScan>
</camelContext>
Copy to Clipboard Toggle word wrap

これにより、名前に Special が含まれるクラスがスキップされます。exclude パターンは、include パターンの前に適用されます。include パターンまたは exclude パターンが定義されていない場合、パッケージで検出されたすべての Route クラスが返されます。

? は 1 つの文字に一致します。* は 0 個以上の文字に一致します。** は完全修飾名の 0 個以上のセグメントに一致します。

7.5. コンテキストスキャンの使用

Camel がコンテナーコンテキスト (たとえば、ルートビルダーインスタンスの Spring ApplicationContext をスキャンできます。これにより、Spring の <component-scan> 機能を使用して、スキャンプロセスで Spring によって作成された RouteBuilder インスタンスを Camel にピックアップさせることができます。

<!-- enable Spring @Component scan -->
<context:component-scan base-package="org.apache.camel.spring.issues.contextscan"/>

<camelContext xmlns="http://camel.apache.org/schema/spring">
    <!-- and then let Camel use those @Component scanned route builders -->
    <contextScan/>
</camelContext>
Copy to Clipboard Toggle word wrap

これにより、Spring @Component を使用してルートにアノテーションを付けるだけで、それらのルートを Camel に含めることができます。

@Component
public class MyRoute extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        from("direct:start")
            .to("mock:result");
    }
}
Copy to Clipboard Toggle word wrap

パッケージスキャンのセクションで説明したように、包含と除外に ANT スタイルを使用することもできます。

第8章 XML IO DSL

xml-io-dsl は、非常に高速でオーバーヘッドの少ない XML パーサーを備えた、Camel に最適化された XML DSL です。これは Camel 固有のソースコード生成パーサーであり、Camel .xml ルートファイル (従来の Spring <beans> XML ファイルではない) のみを解析できます。

Camel XML DSL には、xml-jaxb-dsl の代わりに xml-io-dsl を使用することを推奨します。すべての Camel ランタイムで動作します。

注記

XML IO DSL を使用している場合、camel-spring-boot アプリケーションはデフォルトで src/main/resources/camel/*.xml ファイルを検索します。

この動作を設定するには、camel.springboot.routes-include-pattern プロパティーに別のパスを指定します。

camel.springboot.routes-include-pattern=/path/to/*.xml

8.1. 例

以下の my-route.xml ソースファイルは、Camel CLI または Camel K でロードおよび実行できます。

my-route.xml

<routes xmlns="http://camel.apache.org/schema/spring">
    <route>
        <from uri="timer:tick"/>
        <setBody>
            <constant>Hello Camel K!</constant>
         </setBody>
        <to uri="log:info"/>
    </route>
</routes>
Copy to Clipboard Toggle word wrap

ヒント

xmlns namespace は省略できます。

ルートが 1 つしかない場合は、<routes> の代わりに <route> をルート XML タグとして使用できます。

Camel K での実行

kamel run my-route.xml
Copy to Clipboard Toggle word wrap

Camel CLI を使用した実行

camel run my-route.xml
Copy to Clipboard Toggle word wrap

xml-io-dsl を使用して、Camel Registry にバインドされる一部の Bean を宣言できます。

Bean は XML でプロパティー (nested プロパティーを含む) を定義でき、Bean は XML で宣言できます。以下に例を示します。

Bean 宣言および定義

<camel>

	<bean name="beanFromProps" type="com.acme.MyBean">
		<properties>
			<property key="field1" value="f1_p" />
			<property key="field2" value="f2_p" />
			<property key="nested.field1" value="nf1_p" />
			<property key="nested.field2" value="nf2_p" />
		</properties>
	</bean>

</camel>
Copy to Clipboard Toggle word wrap

xml-io-dsl が使用する高速 XML パーサーのすべての利点を維持しつつ、Camel は他の XML namespace で宣言された XML 要素を処理し、それらを個別に処理することもできます。このメカニズムでは、Spring の http://www.springframework.org/schema/beans namespace を使用して XML 要素を含めることができます。

これにより、Spring Application Context (または Spring Boot) を実際に実行しなくても、Spring Beans の柔軟性が Camel メインにもたらされます。

Spring namespace の要素が見つかると、それらは org.springframework.beans.factory.support.DefaultListableBeanFactory のインスタンスの入力および設定に使用され、Spring 依存関係インジェクションを利用して Bean を接続します。

その後、これらの Bean は通常の Camel Registry を介して公開され、Camel ルートで使用できます。

以下は、ルート定義によって使用されるルートと Bean の両方を定義する camel.xml ファイルの例です。

camel.xml

<camel>

    <beans xmlns="http://www.springframework.org/schema/beans">
        <bean id="messageString" class="java.lang.String">
            <constructor-arg index="0" value="Hello"/>
        </bean>

        <bean id="greeter" class="org.apache.camel.main.app.Greeter">
            <description>Spring Bean</description>
            <property name="message">
                <bean class="org.apache.camel.main.app.GreeterMessage">
                    <property name="msg" ref="messageString"/>
                </bean>
            </property>
        </bean>
    </beans>

    <route id="my-route">
        <from uri="direct:start"/>
        <bean ref="greeter"/>
        <to uri="mock:finish"/>
    </route>

</camel>
Copy to Clipboard Toggle word wrap

my-route ルートは、Spring <bean> 要素を使用して定義された greeter を参照します。

その他の例は Apache Camel JBang ページにあります。

8.2. コンストラクターで Bean を使用する

コンストラクター引数で Bean を作成する場合は、Camel 4.1 以降では、XML タグとして追加できます。以下に例を示します。

Camel 4.1 以降: constructor タグを持つ Bean

<camel>

	<bean name="beanFromProps" type="com.acme.MyBean">
        <constructors>
          <constructor index="0" value="true"/>
          <constructor index="1" value="Hello World"/>
        </constructors>
        <!-- and you can still have properties -->
		<properties>
			<property key="field1" value="f1_p" />
			<property key="field2" value="f2_p" />
			<property key="nested.field1" value="nf1_p" />
			<property key="nested.field2" value="nf2_p" />
		</properties>
	</bean>

</camel>
Copy to Clipboard Toggle word wrap

Camel 4.0 を使用する場合は、type 属性にコンストラクター引数を付ける必要があります。

Camel 4.0: type 属性に constructor 引数を持つ Bean

<bean name="beanFromProps" type="com.acme.MyBean(true, 'Hello World')">
    <properties>
        <property key="field1" value="f1_p" />
        <property key="field2" value="f2_p" />
        <property key="nested.field1" value="nf1_p" />
        <property key="nested.field2" value="nf2_p" />
    </properties>
</bean>
Copy to Clipboard Toggle word wrap

8.3. ファクトリーメソッドからの Bean の作成

Bean は、public static ファクトリーメソッドから作成することもできます。

ファクトリーメソッド XML

	<bean name="myBean" type="com.acme.MyBean" factoryMethod="createMyBean">
        <constructors>
          <constructor index="0" value="true"/>
          <constructor index="1" value="Hello World"/>
        </constructors>
	</bean>
Copy to Clipboard Toggle word wrap

factoryMethod を使用する場合は、引数の constructor タグを指定する必要があります。

たとえば、これは、クラス com.acme.MyBean は以下のようになります。

ファクトリーメソッド

public class MyBean {

    public static MyBean createMyBean(boolean important, String message) {
        MyBean answer = ...
        // create and configure the bean
        return answer;
    }
}
Copy to Clipboard Toggle word wrap

注記

作成したクラスで、ファクトリーメソッドを public static にする必要があります。

8.4. ビルダーイメージからの Bean の作成

以下に示すように、別のビルダークラスから作成された Bean を作成できます。

Builder XML

	<bean name="myBean" type="com.acme.MyBean"
          builderClass="com.acme.MyBeanBuilder" builderMethod="createMyBean">
        <properties>
          <property key="id" value="123"/>
          <property key="name" value="Acme"/>
        </constructors>
	</bean>
Copy to Clipboard Toggle word wrap

注記

no-arg のデフォルトコンストラクターでビルダークラスを public にする必要があります。

その後、ビルダークラスを使用して、Fluent Builder 形式の設定を使用して実際の Bean を作成できます。

Builder クラスのプロパティーを設定し、最後に builderMethod を呼び出して Bean を作成します。

このメソッドは Java リフレクションを介して呼び出します。

8.5. ファクトリー Bean から Bean を作成する

以下のようにファクトリー Bean から Bean を作成できます。

ファクトリー XML

	<bean name="myBean" type="com.acme.MyBean"
          factoryBean="com.acme.MyHelper" factoryMethod="createMyBean">
        <constructors>
          <constructor index="0" value="true"/>
          <constructor index="1" value="Hello World"/>
        </constructors>
	</bean>
Copy to Clipboard Toggle word wrap

ヒント

factoryBean を使用して、FQN クラス名ではなく Bean ID で既存の Bean を参照することもできます。

factoryBean を使用する場合は、引数を constructor タグとして指定する必要があります。

たとえば、com.acme.MyHelper クラスは以下のようになります。

ファクトリー Bean

public class MyHelper {

    public static MyBean createMyBean(boolean important, String message) {
        MyBean answer = ...
        // create and configure the bean
        return answer;
    }
}
Copy to Clipboard Toggle word wrap

注記

ファクトリーメソッドを public static にする必要があります。

8.6. スクリプト言語を使用した Bean の作成

高度なユースケースがある場合は、groovy、java、javascript などのスクリプト言語をインライン化して、Bean を作成できます。

スクリプトを使用すると、より柔軟になり、プログラミングを使用して Bean を作成および設定できます。

スクリプト

	<bean name="myBean" type="com.acme.MyBean" scriptLanguage="groovy">
        <script>
      // some groovy script here to create the bean
      bean = ...
      ...
      return bean
        </script>
	</bean>
Copy to Clipboard Toggle word wrap

注記

script を使用する場合、コンストラクター、ファクトリー Bean、およびファクトリーメソッドは使用されません。

8.7. Bean での init メソッドと destroy メソッドの使用

Bean を使用する前に初期化およびクリーンアップ作業を行う必要がある場合は、Camel によって適切にトリガーされる initMethod および destroyMethod を使用できます。

これらのメソッドは、以下に示すように、public void であり、引数を持ちません。

初期化およびクリーンアップ方法

public class MyBean {

    public void initMe() {
        // do init work here
    }

    public void destroyMe() {
        // do cleanup work here
    }

}
Copy to Clipboard Toggle word wrap

また、これらのメソッドを XML DSL で次のように宣言する必要があります。

初期化とクリーンアップ XML

	<bean name="myBean" type="com.acme.MyBean"
          initMethod="initMe" destroyMethod="destroyMe">
        <constructors>
          <constructor index="0" value="true"/>
          <constructor index="1" value="Hello World"/>
        </constructors>
	</bean>
Copy to Clipboard Toggle word wrap

initMethoddestroyMethod はいずれもオプションであるため、Bean には両方は必要ありません。

8.8. 同じ XML IO DSL ファイル内の REST とルート

同じ DSL ファイルに、REST とルートの両方を含めることができます。

同じ XML IO DSL ファイル内の REST とルート

<camel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://camel.apache.org/schema/spring"
       xsi:schemaLocation="
            http://camel.apache.org/schema/spring
            https://camel.apache.org/schema/spring/camel-spring.xsd">
   <rest id="rest">
        <post id="post" path="start">
            <to uri="direct:start"/>
        </post>
    </rest>

    <route>
        <from uri="direct:start"/>
        <to uri="amqp:queue:Test.Broker.StreamMessage?jmsMessageType=Stream&amp;disableReplyTo=true"/>
    </route>
</camel>
Copy to Clipboard Toggle word wrap

法律上の通知

Copyright © 2025 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

詳細情報

試用、購入および販売

コミュニティー

Red Hat ドキュメントについて

Red Hat をお使いのお客様が、信頼できるコンテンツが含まれている製品やサービスを活用することで、イノベーションを行い、目標を達成できるようにします。 最新の更新を見る.

多様性を受け入れるオープンソースの強化

Red Hat では、コード、ドキュメント、Web プロパティーにおける配慮に欠ける用語の置き換えに取り組んでいます。このような変更は、段階的に実施される予定です。詳細情報: Red Hat ブログ.

会社概要

Red Hat は、企業がコアとなるデータセンターからネットワークエッジに至るまで、各種プラットフォームや環境全体で作業を簡素化できるように、強化されたソリューションを提供しています。

Theme

© 2026 Red Hat
トップに戻る