Cache just doesn't seem to work in clojure, what is the way to use it?

Viewed 61

I'm working on a simple project that shows some data that I'd like to see everyday. This will go on to my raspberry-pi. I'm using a free api that has a limit on requests so I thought I'd cache the requests so I don't spam the API. Here is what I've got so far:

(def KEY "Cache-Key")
(def CF (cache/ttl-cache-factory {} :ttl 43200)) ; 12 hour cache

(defn get-data-from-api
  [url]
  (let [response {:cache true :value 1}]
    (println "---> getting from http")
    response))

(defn get-data
  [url]
  (cache/lookup-or-miss CF KEY (get-data-from-api url)))

According to this link, this is all that is required. Except:

  • my get-data function always gets it from the api (the println I added to debug gets printed always). The cache is being added just fine, just doesn't seem to fetch and return
  • The get-data doesn't return anything. So when I do curl http://localhost:3001/display I get an empty response.

Am I using the cache correctly please?

1 Answers

The last value to lookup-or-miss must be a function that will be called on a cache miss. In your code, you're first calling the function and then pass its result to the lookup function, so your function will be called unconditionally (after all, lookup-or-miss is a regular function itself and not a macro - it can't dictate when its arguments are evaluated).

Even in the article you link to, they pass http-get directly and the url serves as the key, which lookup-or-miss will use as an argument for http-get by default on a cache miss.

Related