forked from strongh/crache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.clj
43 lines (32 loc) · 1.04 KB
/
cache.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
(ns crache.cache
(:require [taoensso.carmine :as car]
[clojure.core.cache :as cache]))
(defmacro wcar* [$ & body]
`(car/wcar (:conn ~$) ~@body))
(defn key-for [$ item]
(str (:key-prefix $) ":" (pr-str item)))
(cache/defcache RedisCache [$]
cache/CacheProtocol
(lookup [_ item]
(delay (wcar* $ (car/get (key-for $ item)))))
(lookup [_ item not-found]
(delay (or (wcar* $ (car/get (key-for $ item))) not-found)))
(has? [_ item]
(= 1 (wcar* $ (car/exists (key-for $ item)))))
(hit [_ item]
(RedisCache. $))
(miss [_ item val]
(let [args (when-let [t (:ttl $)] ["ex" t])
val (if (delay? val) @val val)]
(wcar* $ (apply car/set (key-for $ item) (car/serialize val) args)))
(RedisCache. $))
(evict [_ item]
(wcar* $ (car/del (key-for $ item)))
(RedisCache. $))
(seed [_ base]
(RedisCache. base))
Object
(toString [_] (str $)))
(defn redis-cache-factory
[conn key-prefix & [ttl]]
(cache/seed (RedisCache. {}) {:conn conn :key-prefix key-prefix :ttl ttl}))