Skip to content

Instantly share code, notes, and snippets.

@eklitzke
Created June 10, 2012 23:47
Show Gist options
  • Select an option

  • Save eklitzke/2907750 to your computer and use it in GitHub Desktop.

Select an option

Save eklitzke/2907750 to your computer and use it in GitHub Desktop.
simple clojure agent program
(ns foo.core)
(use 'lamina.core 'lamina.connections 'aleph.http)
(defn print-agent [fmt & rest]
"prints a printf-style message, prefixed by the current agent"
(let [args (if (nil? rest) '(*agent*) (cons *agent* rest))]
(apply printf (str "%s " fmt "\n") args)))
(defn make-get-requests [_ ntimes url]
"get a url some number of times -- meant to be called by an agent"
(print-agent "in make-get-requests")
(let [client (http-client {:url url
:timeout 1000
:method :get})]
(try
(dotimes [n ntimes]
(print-agent "making request %d" n)
(let [response (wait-for-result
(client {}))]
(print-agent "got response %d" n)))
(finally
close-connection client
(print-agent "done with make-get-request")))))
(defn get-urls [parallelism times url]
"use `parallelism` threads to get a `url` `times` times"
(let [agents (repeatedly parallelism #(agent nil))]
(doseq [agent agents] (send-off agent make-get-requests times url))
(apply await-for 5000 agents)
;(doall (map #(deref %) agents))
))
(defn -main
[& args]
(get-urls 2 2 "http://www.example.com/"))
;; After running, output is like:
;
; *agent* in make-get-requests
; *agent* in make-get-requests
; clojure.lang.Agent@4266a968 making request 0
; clojure.lang.Agent@e5bc0a7 making request 0
; clojure.lang.Agent@e5bc0a7 got response 0
; clojure.lang.Agent@e5bc0a7 making request 1
; clojure.lang.Agent@4266a968 got response 0
; clojure.lang.Agent@4266a968 making request 1
; clojure.lang.Agent@e5bc0a7 got response 1
; *agent* done with make-get-request
; clojure.lang.Agent@4266a968 got response 1
; *agent* done with make-get-request
; true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment