LoginSignup
11
10

More than 5 years have passed since last update.

ClojureからApache Camelを使ってみる

Posted at

いろんな定常処理を自動でやってくれるらしいApache CamelをClojureから使ってみたいと思います。

まずは、project.cljでcamel-coreへの依存を設定しておきます。

  :dependencies [[org.apache.camel/camel-core "2.13.0"] [org.clojure/clojure "1.6.0"]]

簡単なファイルコピーのサンプルはこんな感じでできました。
このサンプルではsrc/camel_sampleディレクトリ内のファイルを./out.txtにコピーします。(新しいファイルがあったらコピーし続けます)

camel_sample.clj
(ns camel-sample.core
  (:import [org.apache.camel.impl DefaultCamelContext]
           [org.apache.camel.builder RouteBuilder])
  (:gen-class))

(let [context (DefaultCamelContext.)]
  (.addRoutes context (proxy [RouteBuilder] []
                        (configure [] (.. this
                                          (from "file:src/camel_sample?noop=true")
                                          (to "file:.?fileName=out.txt")))))
  (.start context))

Apache Camelのfile:ではnoop=trueのオプションを指定すると、ファイルの移動の代わりにコピーを行います。
※ちなみにnoop=trueとするとidempotent=trueも設定されるので、同じファイルは複数回コピーされなくなるようです

また、file:のURIフォーマットはfile:directoryName[?options]となっているので、ディレクトリを指定します。単一のファイルを指定したい場合はfileNameのオプションを使えばよいようです。

上のサンプルを関数・マクロとして定義しなおすと、このようにも書けます。

camel_sample_core.clj
(ns camel-sample.core
  (:import [org.apache.camel.impl DefaultCamelContext]
           [org.apache.camel.builder RouteBuilder])
  (:gen-class))

(defn- create-builder [f]
  (proxy [RouteBuilder] [] (configure [] (f this))))

(defmacro add-route [context & body]
  `(.addRoutes ~context (create-builder (fn [~'this] (.. ~'this ~@body)))))

(def c (DefaultCamelContext.))
(add-route c (from "file:src/camel_sample?noop=true")
             (to "file:.?fileName=out.txt"))
(.start c)

とりあえずは動くところまでできました。
ファイルコピー以外にもSSHでのコマンド実行やSFTPやWindowsファイル共有からのファイル取得、さらにはAmazon, Google, Twitter連携なども、簡単なURIを指定するだけで行えるっぽいですね。

11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10