Apache Camel の使用

Apache CamelApache ActiveMQ プロジェクトの一部、Spring を基盤とした統合フレームワークで EIP (Enterprise Integration Patterns) を実現するためのクラスライブラリが用意されている。
なお、EIP ではエンタープライズアプリケーションを連携させるためのメッセージングに関するパターンが定義されている。


というわけで、今回は以下の環境で Apache Camel の簡単なスタンドアロン実行を試してみた。

  • Apache Camel 1.4.0
  • Groovy 1.5.6

Camel を動作させる基本手順は以下の通り。

  1. CamelContext を作成
  2. 必要に応じて Component や Endpoint を設定
  3. ルーティングルール(RouteBuilder 内の DSL, XML などで定義)を追加
  4. CamelContext を start
  5. 終了するには CamelContext を stop

サンプルスクリプトの作成と実行

単一の Groovy スクリプトで CamelContext の作成と開始、エンドポイントの呼び出しを実行する以下のようなサンプルを作成して実行。

sample.groovy ファイル
import org.apache.camel.Processor
import org.apache.camel.builder.RouteBuilder
import org.apache.camel.impl.DefaultCamelContext

class SampleRoute extends RouteBuilder {
    void configure() {
        println "call configure()"

        //DSL を使ったルーティングルールの定義
        from("direct:start").process({println "process $it"} as Processor)
    }
}

//CamelContext 作成
ctx = new DefaultCamelContext()
//ルーティングルールを追加
ctx.addRoutes(new SampleRoute())

template = ctx.createProducerTemplate()

//CamelContext を start
ctx.start()

(1..3).each {
    //direct:start エンドポイント呼び出し
    template.sendBody("direct:start", "test${it}")
}

//CamelContext を stop
ctx.stop()
サンプルの実行
>groovy sample.groovy
call configure()
Created MBeanServer with ID: ・・・
process Exchange[Message: test1]
process Exchange[Message: test2]
process Exchange[Message: test3]