Skip to content

Instantly share code, notes, and snippets.

@bdevel
Created January 27, 2023 20:09
Show Gist options
  • Save bdevel/e221c104287d1f9036414caf35f5f02e to your computer and use it in GitHub Desktop.
Save bdevel/e221c104287d1f9036414caf35f5f02e to your computer and use it in GitHub Desktop.
Clojure memoize function using a custom cache key
(ns example.cache-util
(:require [clojure.core.cache :refer [lru-cache-factory ttl-cache-factory]]
[clojure.core.cache.wrapped :refer [lookup-or-miss]]
))
(defmacro defn-lru-ttl-cached-by-key
"Defines function name, which will cache using the return value of key-fn which is passed args.
If cache miss, will run the value-forms which will have args in scope."
[name doc
max-qty ttl-ms
key-fn args & value-forms]
`(do
(def cache-name# (atom (lru-cache-factory
(ttl-cache-factory {} :ttl ~ttl-ms)
:threshold ~max-qty)))
(defn ~name
~doc
~args
(let [cache-key# (apply ~key-fn ~args)]
(lookup-or-miss cache-name# cache-key#
(fn [_#]
~@value-forms))))))
(comment
(defn-lru-ttl-cached-by-key
my-fetcher
"will sleep and return a value"
5 (* 1000 3)
#(:id %)
[item]
(Thread/sleep 1000)
(:value item))
(my-fetcher {:id "bob2" :value 12})
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment