5

嗨,我正在使用 ColdFusion 调用 last.fm api,使用来自此处的 cfc 包。

我担心会超过请求限制,即每个原始 IP 地址每秒 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 的新点击?

想知道如何最好地解决这个问题

谢谢

4

2 回答 2

3

由于它是简单的数据模型,因此我不会使用自定义缓存引擎使事情复杂化。我会把简单的 struct/query : searchTerm/result,timestamp 放在某个地方。在那里你可以这样做:

<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>

编辑:是的,您还应该在某个地方放置一个方法,该方法将删除时间戳差异为 gt 的结构键,然后是您的缓存有效期。

建议使用外观图案,以便将来可以更改。

抱歉有错别字:)

于 2010-04-26T10:49:11.417 回答
0

我会尝试自定义缓存。

它可以是一个结构,其中键是艺术家姓名或条目的其他唯一标识符。

如果您使用的是 CF9 或 Railo 3.1.2+,您可以使用内置缓存(函数 CachePut、CacheGet 等),它可以为您处理超时等问题。

否则,您可以将缓存存储到应用程序范围内,但需要在每个条目中包含时间戳,并在缓存事件(get/put/remove)甚至每个请求上检查它。

于 2010-04-26T10:25:20.767 回答