Skip to content

Instantly share code, notes, and snippets.

@joshrotenberg
Created October 21, 2015 23:20
Show Gist options
  • Save joshrotenberg/4d394ae7c96b89da3309 to your computer and use it in GitHub Desktop.
Save joshrotenberg/4d394ae7c96b89da3309 to your computer and use it in GitHub Desktop.
(ns rediscache
(:require [taoensso.carmine :as car :refer (wcar)])
(:require [clojure.core.cache :as cc]
[clojure.core.memoize :refer [build-memoizer]])
(:import clojure.core.memoize.PluggableMemoization))
(def server1-conn {:pool {} :spec {:host "localhost" :port 6379}}) ;; XXX config here
(defmacro wcar* [& body] `(car/wcar server1-conn ~@body))
(cc/defcache RCache [cache name ttl]
cc/CacheProtocol
(lookup [this item]
(delay (wcar* (car/get (str name ":" item)))))
(lookup [this item not-found]
(delay (or (wcar* (car/get (str name ":" item))) not-found)))
(has? [this item]
(= 1 (wcar* (car/exists (str name ":" item)))))
(hit [_ item]
(RCache. cache name ttl))
(miss [this item val]
(let [v (if (delay? val) @val val)]
(if ttl
(wcar* (car/set (str name ":" item) (car/serialize v) "ex" ttl))
(wcar* (car/set (str name ":" item) (car/serialize v))))
(RCache. cache name ttl)))
(evict [this item]
(wcar* (car/del (str name ":" item)))
(RCache. cache name ttl))
(seed [this base] (doseq [[k v] base] (cc/miss this k v)) this)
Object
(toString [_] (str cache)))
(defn redis-cache-factory
[name & {:keys [ttl seed]
:or {ttl nil
seed {}}}]
(cc/seed (RCache. {} name ttl) seed))
(defn memo
[f name & {:keys [ttl seed]
:or {ttl nil
seed {}}}]
(build-memoizer #(PluggableMemoization. %1
(redis-cache-factory name :ttl ttl :seed seed))
f))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment