在clojure中缓存解析的数据

caching parsed data in clojure

假设我做了一些解析来生成数据集。这项工作可能非常缓慢,加载显示数据集的网页也是如此。

有没有办法告诉服务器每分钟解析一次say,缓存这个并依赖缓存来显示结果。

我看过 core.cache and its docs,但我想不出一个简单的方法来做到这一点:

(require '[clojure.core.cache :as cache])

(def Dataset 
  (atom 
    (-> (parse-fn "http://nytimes.com")
        (cache/ttl-cache-factory :ttl 20000))) 

如何刷新缓存我可以依赖它吗?

(build-html-table @Dataset)

谢谢!

您可以启动一个额外的线程来处理数据更新(请参阅 this question 以了解定期 运行 函数的方法),例如:

(defonce data (atom nil))
(defonce updater
  (future
    (while true
      (reset! data (parse-fn "http://nytimes.com"))
      (Thread/sleep 60000))))

访问数据:

@data

要取消更新:

(future-cancel updater)

确保处理 parse-fn 内的异常。此外,您可能希望等待初始数据可用,这可以使用从 updater.

中获取 delivered 的 promise 来实现

core.cache 不会真正适用于您的情况,除非您可以接受在 TTL 过期后进入的请求必须等到数据返回到缓存中。此外,当缓存函数结果时 core.memoize 已经为您完成了大部分工作:

(require '[clojure.core.memoize :as memo])
(defn fetch-dataset!
  (memo/ttl
    #(parse-fn "http://nytimes.com")
    :ttl/threshold 60000))

(fetch-dataset!) ;; => <your data> (takes a while)
(fetch-dataset!) ;; => <your data> (immediately)
... 60s ...
(fetch-dataset!) ;; => <your data> (takes a while)