マルチスレッドでWebページを取得する

HttpClientを使って、マルチスレッドでWebページを取得するサンプル。
leiningenを使う場合は、project.cljの:dependenciesに[commons-httpclient"3.1"]を記述し、lein depsを実行すればライブラリを取得してくれる。

(ns web-get
  (:import [org.apache.commons.httpclient HttpClient MultiThreadedHttpConnectionManager])
  (:import [org.apache.commons.httpclient.methods GetMethod]))

(defn fetch [client url]
  (let [get (GetMethod. url)]
    (println (str "Fetching: " url))
    (try
      (let [status (.executeMethod client get)]
	(println (str "Got " url ": " status)))
      (finally
       (.releaseConnection get)))))

(def client (HttpClient. (MultiThreadedHttpConnectionManager.)))
(def pages ["http://www.yahoo.co.jp/" "http://www.google.com/" "http://localhost/"])

(defn do-it []
  (doseq [url pages]
    (.start (Thread. (fn [] (fetch client url))))))

実行結果

user> (in-ns 'web-get)
#<Namespace web-get>
web-get> (do-it)
nil
Fetching: http://www.yahoo.co.jp/
Fetching: http://www.google.com/
Fetching: http://localhost/
Got http://localhost/: 200
Got http://www.yahoo.co.jp/: 200
Got http://www.google.com/: 200

動いた。\(^▽^)/

参考URL