簡體   English   中英

在 clojure 中緩存 api 調用

[英]Caching api calls in clojure

我想在 clojure 中實現 api 的緩存,在我的應用程序中,我有 api,它們被調用用於某些功能。 我想減少那個 api 調用。 我想使用在clojure.core.cache.wrapped上實現的clojure.core.cache 我想根據 url 緩存我的 api 調用響應。 url 是 GET 並且在 url 中有查詢來區分響應

for eg
http://localhost:3000/:clientid/get_data

示例代碼


(:require [clojure-mauth-client.request :refer [get!]]
          [clojure.core.cache.wrapped :as cw])


(def my-cache (cw/ttl-cache-factory {} :ttl 60000))

(defn get-data-caller [cid]
  (cw/lookup-or-miss my-cache cid get-data))

(defn get-data [cid]
(let [req-url (str "/api/get-data?id=" cid)
      response (retry-request (sign-credentials #(get! base-url req-url)) 3)]
(println response))))

我想以一種根據cid緩存的方式實現。 在上面的代碼 3 是最大重試次數

通過當前的實現,我得到了以下錯誤。

In my current code it is calling the api again and again

我得到了解決方案,我在這里犯的主要錯誤是我在get-data-caller中實現了這個

lookup-or-miss實際上接受 3 個參數

lookup-or-miss [cache key fn]

Here 
1. cache is the one that we create.
2. key that we want to use as 'key' in our caching
3. The third has to be the function, that takes 'key' as an arg and gets data for us. 

So lookup-or-miss will first check if the we have cached data for the 'key' passed, if not then, that will be passed as an arg to the third arg (i.e the fn) and get the fresh data.

如果 key 的緩存數據不存在,則第三個 arg 中的 fn 將以 key 作為 arg 調用以獲取數據。

有了以上理解,我確實重寫了我的代碼,如下所示

(:require [clojure-mauth-client.request :refer [get!]]
          [clojure.core.cache.wrapped :as cw])


(def my-cache (cw/ttl-cache-factory {} :ttl 60000))

(defn http 
[url]
(retry-request (sign-credentials #(get! url)) 3))

(defn get-data-caller [cid]
  (get-data cid))

(defn get-data [cid]
(let [req-url (str "/api/get-data?id=" cid)
      response (cw/lookup-or-miss my-cache req-url http-request)]
(println response))))

所以這里的lookup-or-miss將在my-cache中搜索req-url鍵,如果存在它將直接返回存儲的值,如果沒有則它將調用http-requestreq-url作為arg

所以lookup-or-miss將像這樣執行;

用於理解的偽代碼

(if (contains? my-cache req-url)
     (:req-url my-cache)
     (http-request req-url))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM