尝试使用Apache Camel来整合Clojure

我想用Clojure尝试使用据说可以自动执行各种常规处理的Apache Camel。

首先,您需要在项目的project.clj文件中设置依赖项camel-core。

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

在这个样本中,我们可以用类似的方式轻松复制文件。
这个样本将 src/camel_sample 目录内的文件复制到 ./out.txt。(如果有新文件,会不断复制)

(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选项即可。

如果将上面的示例重新定义为函数或宏,也可以这样写。

(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文件共享中獲取文件,甚至還可以通過簡單的URI指定來實現與Amazon、Google、Twitter等的連接。

bannerAds