缓存API呼叫Clojure
我想在Clojure中实现API的缓存,在我的应用程序中,我的API被要求使用某些功能。我想减少API调用。我想使用clojure.core.cache.cache.trapped
,该是在clojure.core.cache
上实现的。我想在URL上缓存我的API呼叫响应基础。 URL在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
I want to implement caching of api in clojure, In my application I have api's which are called for some of the functionalities. I want to reduce that api calls. I want to use clojure.core.cache.wrapped
which is implemented upon clojure.core.cache
. I want to cache my api call response base on the url.
The url is GET and has query inside the url that differentiates the response
for eg
http://localhost:3000/:clientid/get_data
Sample code
(: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))))
I want to implement in a way that it caches depending on the cid
.
In above code 3 is max-retries
With current implementation I am getting below error.
In my current code it is calling the api again and again
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我得到了解决方案,我在这里犯的主要错误是我在
get-data-caller
lookup-or-miss
实际上接受3个参数,如果键的缓存数据不存在,则第三个ARG中的FN将与关键为获取数据。
有了以上的理解,我确实在下面重写了我的代码
,因此在此处查找或错过将搜索
req-url
在my-cache
中,如果存在,它将直接返回值存储的,如果不是这样,它将用req-url
作为arg 调用http-request
作为arg,因此查找或失踪将被执行。
伪理解的伪代码
I got the solution, The main mistake I made here is that I implemented this in
get-data-caller
lookup-or-miss
actually accepts 3 paramsIf the cache data is not present for the key, then the fn in the third arg will be called with key as arg to get the data.
With above understanding I did rewrite my code as below
So here lookup-or-miss will search
req-url
key inmy-cache
, if present it will directly return the value stored, if not then it will callhttp-request
withreq-url
as an argSo lookup-or-miss will be executed something like this;
pseudo code for understanding