2014.4.18
須江信洋(@nobusue)
http://d.hatena.ne.jp/nobusue
https://www.facebook.com/nobuhiro.sue
G*ワークショップZ
Apache Camel+Groovyで
簡単システム統合ハンズオン
2
自己紹介
 須江 信洋(すえ のぶひろ)
 Twitter: @nobusue
 https://www.facebook.com/nobuhiro.sue
 約10年ほどJavaEE関連の仕事をしてます
 2013年10月よりフリーランス(個人事業主)
 最近興味を持っているもの
 Vert.x / Storm / Camel / Elasticsearch
 Vagrant / Docker / Ansible / Serverspec
 もちろんGroovy / Gradle / Grails
Gradle本
(執筆中)
3
JGGUGって?
 Japan Grails/Groovy User Group
 2009年発足
 Grails/GroovyなどのGroovyエコシステム(G*)に
関するコミュニティ
 前身は2006年から活動していたGrailsコミュニティ
 こわくない
 毎月第3金曜日にG*ワークショップを開催
 参加型(ハンズオンなど)
 告知・申し込みはこちら
 http://jggug.doorkeeper.jp/
http://www.jggug.org/
4
Today’s Agenda
 Groovyインストール
 Apache Camel概要
 EIP(Enterprise Integration Patterns)
 Camelのアーキテクチャ
 Camel+Groovyハンズオン
 File
 DB / JMS
 Timer / VM
 Twitter / Elasticsearch
 参考情報
本日のGOAL
Apache Camelの最新情報を知る
Apache Camelを技術的に詳しく突っ込む
Apache Camelの概要を知る
Apache Camelに触れてみる
⇒入口の敷居を下げるのが目的です
6
Groovyインストール
 前提
 JDK1.7以上 (“java –version”で確認)
 GVM利用
 curl -s get.gvmtool.net | bash
 gvm install groovy
 詳細は http://gvmtool.net/ 参照
 Windowsの場合はcygwinが必要
 ZIPを展開
 http://groovy.codehaus.org/Download
 安定版は2.2.2が最新(2014/4/17現在)
 適当なディレクトリに展開 ($GROOVY_HOME)
 $GROOVY_HOME/bin にパスを通しておく
7
Groovy動作確認
GVMでインストールした場合は
~/.gvm/groovy/<version> 以下に導入され、
~/.gvm/groovy/current にシンボリックリンクが
作成されます。
$ groovy -v
Groovy Version: 2.2.2 JVM: 1.7.0_45 Vendor: Oracle
Corporation OS: Mac OS X
8
Apache Camel 概要
 汎用的なシステム統合フレームワーク
 Enterprise Integration Pattens(EIP)
 EIP本が先にあり、その実装を提供する目的とか?
 OSS(Apache2.0ライセンス)
 Javaで実装、軽量(組み込み利用も可)
 DSLでルーティング・メディエーションを定義
 Java/Spring/Scala/Groovyなど豊富なDSL
 豊富な連携先(100以上?)
https://camel.apache.org/
9
Enterprise Integration Patterns
 システム統合のパターンカタログ
 http://www.eaipatterns.com/toc.html
分厚い!
10
Enterprise Integration Patterns
 以下の分類でパターンを整理
 Integration Styles (File/DB/RPC/Messaging)
 Messaging Systems
 Messaging Channels (P2P/PubSub/Bus)
 Message Construction (要求応答/Corr.)
 Message Routing (CBR/Splitter/Aggregator)
 Message Transformation (Envelope/Filter)
 Messaging Endpoints (GW/Polling/Dispatcher)
 System Management
11
Camelのアーキテクチャ
http://camel.apache.org/architecture.html
12
Component / Endpoint
 Component
 連携先ごとに用意された実装部品
 Endpoint
 CamelからComponentに連携するための
インターフェース
 Component固有のURI(URL)を定義
例) file://, twitter://
13
Camelが連携可能なシステム
http://camel.apache.org/components.html
14
Apache Camel 利用方法
 基本
 何らかの手段でCamelのライブラリを入手
 CamelContextのインスタンスを作る
 RouteBuilderでメディエーションを定義
 contextにメディエーションを追加
 context.start()
 具体的にはこのへんを参照
 http://acro-engineer.hatenablog.com/entry/2013/11/27/112423
 http://sourceforge.jp/projects/cameluserjp/wiki/%E5%88%9D%
E3%82%81%E3%81%A6%E3%81%AECamel
https://camel.apache.org/
15
ちょっと敷居高くないですか?
 いきなりMavenとか・・・
 いきなりEclipseとか・・・
 システム統合って、もっとシェルスクリプトっぽ
い使い方を期待しますよね?
 そこでGroovyですよ!
 JARの事前ダウンロード ⇒不要
 コンパイル ⇒不要
 Eclipse ⇒不要
 エディタで書いて、その場でサクッと動かせます!
16
ハンズオン
 Hello Camel (File to File)
 Timer
 DB(SQL)
 SEDA / VM
 Test
 (Twitter -> Elasticsearch)
 スクリプト以外の実行方法(Gradle)
17
サンプルコード
 GitHubで公開しています
 https://github.com/nobusue/camel-goorvy
 基本はJDKとGroovyのみで実行できます
 連携先となるソフトウェアを使う場合があります
 必要に応じて解説します
 本日のきっかけとなったエントリはこちらです
 http://saltnlight5.blogspot.jp/2012/08/getting-started-
with-apache-camel-using.html
18
Hello Camel
 適当な作業ディレクトリを作成
 サンプル: helloCamel
 ”FileCopierWithCamel.groovy”を作成
 実行
 groovy FileCopierWithCamel.groovy
 data/inbox/ 以下にファイルを置いてみる
 ログが出力され、
data/outbox/ 以下にファイルがコピーされる
 60秒後に停止
19
FileCopierWithCamel.groovy
@Grab('org.apache.camel:camel-core:2.13.0')
@Grab('org.slf4j:slf4j-simple:1.7.6')
import org.apache.camel.*
import org.apache.camel.impl.*
import org.apache.camel.builder.*
def context = new DefaultCamelContext()
context.addRoutes(new RouteBuilder() {
public void configure() {
from("file:data/inbox?noop=true")
.to("log://camelLogger?level=INFO")
.to("file:data/outbox") }})
context.start()
Thread.sleep(60000)
context.stop()
20
実行結果
[main] INFO org.apache.camel.component.file.FileEndpoint - Endpoint is
configured with noop=true so forcing endpoint to be idempotent as well
[main] INFO org.apache.camel.component.file.FileEndpoint - Using default
memory based idempotent repository with cache max size: 1000
[main] INFO org.apache.camel.impl.DefaultCamelContext - Route: route1
started and consuming from: Endpoint[file://data/inbox?noop=true]
[main] INFO org.apache.camel.impl.DefaultCamelContext - Total 1 routes,
of which 1 is started.
[main] INFO org.apache.camel.impl.DefaultCamelContext - Apache Camel
2.13.0 (CamelContext: camel-1) started in 0.541 seconds
[Camel (camel-1) thread #0 - file://data/inbox] INFO camelLogger –
Exchange[ExchangePattern: InOnly, BodyType:
org.apache.camel.component.file.GenericFile, Body: [Body is file based:
GenericFile[test.txt]]]
@Grab ???
 Groovyの言語機能の一つ
 スクリプト中に記述するだけで以下を実行
 Mavenリポジトリ等からのライブラリ取得
 クラスパスへの追加
 (必要に応じてキャッシュ)
 Grapeという管理用コマンドもあり
 Apache Ivyを利用して実装されている
22
Timer(JDK Timer)
 https://github.com/nobusue/camel-groovy/tree/master/timer
context.addRoutes(new RouteBuilder() {
public void configure() {
from("timer://jdkTimer?period=3000")
.to("log://camelLogger?level=INFO")
}
})
context.start()
addShutdownHook{ context.stop() }
synchronized(this){ this.wait() }
要件が複雑なら
Quartzコンポーネ
ントがおすすめ
23
DB(SQL)
 DBからSQLでデータを抽出
 https://github.com/nobusue/camel-groovy/tree/master/sql
 組み込みDerbyを利用
 SpringのEmbeddedDatabaseBuilder()
 実行
 groovy SQL.groovy
 data/ 以下にダンプが出力される
24
DBセットアップ
def db = new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.DERBY)
.addScript("create.sql")
.build()
def reg = new SimpleRegistry()
reg.put("myDS", db)
Camelから利用するため、
Datasourceをレジストリに
登録しておく
(JNDIでも可)
25
SQL実行 / ダンプ出力
context.addRoutes(new RouteBuilder() {
public void configure() {
from("timer://jdkTimer?period=1000")
.setBody(constant("select * from projects"))
.to("jdbc:myDS")
.process(new Processor() {
def void process(Exchange exchange) {
def body = exchange.getIn().getBody()
def newBody = []
body.each{ newBody << "${it.toString()}" }
exchange.getIn().setBody(newBody.join("¥n"))
}
}).to("file:dump")
}
})
Processor()を利用して
自由に処理できる
(TypeConverterは面倒)
http://camel.apache.org/processor.html
26
Camel内メッセージング
 Camelの内部処理はメッセージング
 メモリ上のBlockingQueueで管理
 Routeから明示的に利用する場合は以下のコ
ンポーネントを利用する
 SEDA ( seda:/ )
 単一CamelContext内のみ有効
 Staging Event-driven Architecture
 VM ( vm:/ )
 同一JVM内で共有可能
 SEDAを継承
27
Test支援Component
 Direct ( direct:/ )
 同期型endpoint
 イベントを与えないと動かない
 Mock ( mock:/ )
 イベントの履歴を記録・検証可能なendpoint
 Test ( test:/ )
 プル型のテストを実施するためのendpoint
 Mockを継承
 DataSet ( dataset:/ )
 endpointへの入力データ
 テスト時の検証データ
28
Twitter -> Camel -> ES (未完成)
 https://github.com/nobusue/camel-groovy/tree/master/twitter-
elasticsearch
context.addRoutes(new RouteBuilder() {
public void configure() {
from("twitter://search?type=direct&keywords=camel"+
"&consumerKey=xxxx"+
"&consumerSecret=xxxx"+
"&accessToken=xxxx"+
"&accessTokenSecret=xxxx")
.marshal().json(JsonLibrary.Jackson)
.to("elasticsearch://elasticsearch?operation=INDEX"+
"&indexName=twitter&indexType=tweet")
}
})
29
スクリプト以外の実行方法
 ビルド⇒JAR化してスタンドアロン実行
 Camel Maven Archetypes
 http://camel.apache.org/camel-maven-archetypes.html
 Gradleテンプレート
 https://github.com/nobusue/camel-groovy/tree/master/gradle-template
 Webコンテナに組み込む
 Servlet Tomcat Example
 https://camel.apache.org/servlet-tomcat-example.html
 Grails: Apache Camel Plugin
 http://www.grails.org/plugin/routing
30
Camelを拡張する
 Java(Groovy)クラスを直接利用
 Bean Component (bean://)
 JNDIに登録したクラスのメソッドが実行可能
 詳しくはこちら
 http://camel.apache.org/bean.html
 独自Componentを実装
 詳しくはこちら (すいませんちゃんと読んでないです・・)
 http://camel.apache.org/writing-components.html
31
Apache Camelの情報源
 本家
 http://camel.apache.org/documentation.html
 日本Apache Camelユーザ会
 http://sourceforge.jp/projects/cameluserjp/
 Apache Camel入門
 http://acro-engineer.hatenablog.com/entry/2013/11/27/112423
 Apache Camel Wiki
 http://wiki.buildria.com/camel/start
 Camel In Action の1章の適当邦訳
 http://etc9.hatenablog.com/entry/20110422/1303450895
Apache Camelの書籍
 Camel in Action
 http://www.manning.com/ibsen/
 Apache Camel Developer's Cookbook
 http://www.packtpub.com/apache-camel-developers-
cookbook/book
 Instant Apache Camel Message Routing
 http://www.packtpub.com/apache-camel-message-
routing/book
 Instant Apache Camel Messaging System
 http://www.packtpub.com/apache-camel-messaging-
system/book
http://camel.apache.org/books.html
_人人人人人人人人人人人人_
> 日本語書籍がなかったッ <
 ̄Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^Y^Y ̄
33
ありがとうございました
https://www.facebook.com/orehiji

Gws 20140418 camel_groovy