Skip to content

Instantly share code, notes, and snippets.

@x
Created April 22, 2015 16:08
Show Gist options
  • Save x/3b43528d50915798f7b2 to your computer and use it in GitHub Desktop.
Save x/3b43528d50915798f7b2 to your computer and use it in GitHub Desktop.
Atomic clojure.cache example
(require '[[clojure.cache :as cache]
[clojure.string :as string]
[cb-statsd :as statsd]])
(def STATSD_SAMPLE_RATE 0.01)
(defn get-statsd-path
[f]
(as-> (str (type f)) fname ;; returns something like "class namespace$foo"
(last (string/split fname #" ")) ;; parse out the "class "
(string/replace fname "$" "."))) ;; use a dot to seperate namespace
(defn update-cache
[cache f & args]
(if (cache/has? cache args)
(do
(statsd/increment (str (get-statsd-path) ".cache-hit") 1 STATSD_SAMPLE_RATE)
(cache/hit cache args))
(do
(statsd/increment (str (get-statsd-path) ".cache-miss") 1 STATSD_SAMPLE_RATE)
(cache/miss cache args (f args)))))
(def my-cache (atom (cach/ttl-cache-factory {} :ttl 1000000)))
(defn my-fn
[a b c]
(+ a b c))
(defn -main
...
(swap! my-cache update-cache my-fn 1 2 3)
(cache/lookup @my-cache [1 2 3]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment