使用coldfusion使用缓存对API的速率限制调用
-
01-10-2019 - |
题
嗨,我正在使用ColdFusion致电Last.fm API,使用来自CFC捆绑包。 这里.
我担心要限制请求限制,这是每秒发起的5个请求,在5分钟内平均。
CFC捆绑包具有一个中央组件,该组件调用所有其他组件,这些组件被分为“艺术家”,“轨道”等部分,该部分“ lastfmapi.cfc”。在我的应用程序中启动,并持续到应用程序的寿命
// Application.cfc example
<cffunction name="onApplicationStart">
<cfset var apiKey = '[your api key here]' />
<cfset var apiSecret = '[your api secret here]' />
<cfset application.lastFm = CreateObject('component', 'org.FrankFusion.lastFm.lastFmApi').init(apiKey, apiSecret) />
</cffunction>
现在,如果我想通过处理程序/控制器致电API,例如我的艺术家处理程序...我可以做到这一点
<cffunction name="artistPage" cache="5 mins">
<cfset qAlbums = application.lastFm.user.getArtist(url.artistName) />
</cffunction>
我对缓存有些困惑,但是正在缓存该处理程序中的每个API 5分钟,但这会有所不同,因为每次有人击中新的艺术家页面时,这仍然不算是对API的重新打击?
想知道如何最好地解决这个问题
谢谢
解决方案
由于这是简单的数据模型,我不会用自定义的缓存引擎使事情变得复杂。我将简单的结构/查询放置:搜索术语/结果,时间戳在某个地方。在那里您可以做到这一点:
<cffunction name="artistPage" cache="5 mins">
<cfargument name="artistName" type="string" required="true"/>
<cfif structKeyExists(application.artistCache, arguments.artistName) and structfindkey(application.artistCache, arguments.artistName)>
<cfif (gettickcount() - application.artistCache[arguments.artistName].timestamp ) lte 5000 >
<cfset result = application.artistCache[arguments.artistName].result >
<cfelse>
<cfset qAlbums = application.lastFm.user.getArtist(arguments.artistName) />
<cfset tempStruct = structnew()>
<cfset structNew.result = qAlbums >
<cfset structNew.timestamp = getTickCount() >
<cfset structInsert(application.artistCache, arguments.artistName, tempstruct, true) >
<cfset result = qAlbums >
</cfif>
<cfreturn result >
</cffunction>
编辑:是的,您应该放置某个方法,该方法将删除struct键,其中时间戳差为GT,然后您的缓存有效期。
建议采用立面模式,以使其在将来变化。
抱歉,错别字:)
其他提示
我会尝试自定义缓存。
它可以是钥匙是艺术家名称或您条目的其他唯一标识符的结构。
如果您使用的是CF9或Railo 3.1.2+,则可以使用内置的缓存(函数cacheput,cacheget等),它可以为您处理超时和东西。
否则,您可以将缓存存储到应用程序范围中,但需要在每个条目中包括时间戳,并在缓存事件(获取/put/删除)甚至每个请求中检查它。
不隶属于 StackOverflow