monger/src/clojure/monger/cache.clj
2012-08-12 05:31:14 +04:00

54 lines
1.4 KiB
Clojure

(ns ^{:doc "clojure.core.cache implementation(s) on top of MongoDB.
Related documentation guide: http://clojuremongodb.info/articles/integration.html"
:author "Michael S. Klishin"}
monger.cache
(:require [monger.collection :as mc]
[clojure.core.cache :as cache])
(:use monger.conversion)
(:import clojure.core.cache.CacheProtocol))
;;
;; Implementation
;;
(def ^{:const true}
default-cache-collection "cache_entries")
;;
;; API
;;
(defrecord BasicMongerCache [collection])
(extend-protocol cache/CacheProtocol
BasicMongerCache
(lookup [c k]
(:value (mc/find-map-by-id (:collection c) k)))
#_ (lookup [c k not-found]
(if-let [doc (mc/find-map-by-id (:collection c) k)]
(:value doc)
not-found))
(has? [c k]
(not (nil? (mc/find-by-id (get c :collection) k))))
(hit [this k]
this)
(miss [c k v]
(mc/insert (get c :collection) {:_id k :value v})
c)
(evict [c k]
(mc/remove-by-id (get c :collection) k)
c)
(seed [c m]
(mc/insert-batch (get c :collection) (map (fn [[k v]]
{:_id k :value v}) m))
c))
(defn basic-monger-cache-factory
([]
(BasicMongerCache. default-cache-collection))
([collection]
(BasicMongerCache. collection))
([collection base]
(cache/seed (BasicMongerCache. collection) base)))