Skip to content
fogus edited this page Jun 15, 2012 · 5 revisions

TTL cache

The time-to-live cache is one that evicts items that are older than a time-to-live threshold (in milliseconds).

General usage

To create a core.cache TTLCache instance you should always use its associated constructor function ttl-cache-factory with an optional :ttl parameter:

    (ns your.lib 
      (:require [clojure.core.cache :as cache]))
	
    (def C (cache/ttl-cache-factory {} :ttl 1000))
    
    (-> C (assoc :a 1) (assoc :b 2))
	;=> {:a 1, :b 2}

note: the default :ttl value is 2 seconds

At this point the cache is fresh and younger than one second (that is, depending on how fast you read), but if you execute yet another call the story will change:

    (defn sleepy [e t] (Thread/sleep t) e)
    
    (-> C (assoc :a 1) 
	      (assoc :b 2)
		  (sleepy 1500)
	      (assoc :c 3))
	;=> {:c 3}

At this point the operation of the TTL cache is exposed. As you see, sleeping in between adding the keys :a and :b causes them to be evicted on the next insertion.

TTL cache use cases

TODO

Clone this wiki locally