Skip to content

Instantly share code, notes, and snippets.

@BadUncleX
Last active April 11, 2018 02:34
Show Gist options
  • Save BadUncleX/4eee704cfdf599563ea929d4c0b83d1d to your computer and use it in GitHub Desktop.
Save BadUncleX/4eee704cfdf599563ea929d4c0b83d1d to your computer and use it in GitHub Desktop.
atom cache 缓存
;;
;; 定制缓存,可以通过meta清理缓存
;;
(defn manipulable-memoize [function]
(let [cache (atom {})]
(with-meta (fn [& args]
(or (second (find @cache args))
(let [ret (apply function args)]
(swap! cache assoc args ret) ret)))
{:cache cache})))
(def slowly (fn [x] (Thread/sleep 3000) x))
;; 调用两次 slowly方法
(time [(slowly 9) (slowly 9)])
(def sometimes-slowly (manipulable-memoize slowly))
;;调用两次 sometimes-slowly 方法, 第二次会使用到缓存
(time [(sometimes-slowly 108) (sometimes-slowly 108) ] )
;; 操纵缓存的meta data
(meta sometimes-slowly)
;; => {:cache #object[clojure.lang.Atom 0x6a45de93 {:status :ready, :val {(108) 108, (100) 100}}]}
(let [cache (:cache (meta sometimes-slowly))]
(swap! cache dissoc '(108)))
;;
;; clojure.core
;;
(comment
(defn memoize
"Returns a memoized version of a referentially transparent function. The
memoized version of the function keeps a cache of the mapping from arguments
to results and, when calls with the same arguments are repeated often, has
higher performance at the expense of higher memory use."
{:added "1.0"
:static true}
[f]
(let [mem (atom {})]
(fn [& args]
(if-let [e (find @mem args)]
(val e)
(let [ret (apply f args)]
(swap! mem assoc args ret)
ret))))))
(ns atom_cache.rotary)
;;
;; from: rotary.client
;; 官方memoize用法之一举例
;; 原来的方法加星号, 需要缓存的方法通过def定义, 借助memoize缓存
;;
(defn- db-client*
"Get a AmazonDynamoDBClient instance for the supplied credentials."
[cred]
(let [aws-creds (BasicAWSCredentials. (:access-key cred) (:secret-key cred))
client (AmazonDynamoDBClient. aws-creds)]
(when-let [endpoint (:endpoint cred)]
(.setEndpoint client endpoint))
client))
(def db-client
(memoize db-client*))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment