使用Memcached和Coldfusion

时间:2013-01-16 16:49:52

标签: coldfusion memcached coldfusion-9

我第一次尝试使用memcached,但在涉及动态变量的查询时我有几个问题。

这是我目前为止的代码示例。我把一切都搞定了,但如果你发现我的代码有任何错误,请告诉我。

    <cfoutput>
    <cfset variables.memcachedFactory = createObject("component","memcachedfactory").init("127.0.0.1:11211")>
    <cfset variables.memcached = variables.memcachedFactory.getmemcached()>

    <cfset email = "sbcglobal"> //Pretend that this is a list with multiple choices for the user to choose from. 


//The query below would have multiple outputs based on the selection of the user above 
    <cfquery name="test" datasource="#ds#">
        select top 10 * from contact where email like '%#email#%'
    </cfquery>

//Setting the key
    <cfset set100 = variables.memcached.set(key="queryTest2",value=test,expiry="5000")>

//Getting the key
    <Cfset test6 = variables.memcached.get("queryTest2")>

    <br><br>this is the query test - did we retrieve it correctly?  - <br />

    <Cfdump var="#Test6#"><br />

    </cfoutput>

现在,我是否必须为查询的每个可能结果设置密钥? (在我的情况下,这将是几百个键,以涵盖所有可能的结果) 我的理解是,memcached在第一个请求之后将值保存到一个键,然后在没有db调用的情况下获得输出。 如果我在我的情况下使用memcached,那只会浪费代码,因为根据用户的选择,每个查询会有所不同吗?

另外,如果输出发生变化,如何更新缓存中的值?这是我必须手动完成的吗?我的数据库每天获得100个交易,上午10点的select * from contacts下午5点将没有相同的输出

1 个答案:

答案 0 :(得分:1)

缓存背后的想法(在这种情况下)是你首先检查memcached,如果密钥存在,你从缓存中获取数据。如果它不存在,则转到数据库,获取数据,将其粘贴到memcached中,然后将其返回给用户。

对于您的用例,您需要为要返回的每个唯一记录集添加唯一键。举个例子。如果电子邮件地址是您用于标识记录集的唯一键,则将其用作memcached中的键。伪代码:

<cfset results = variables.memcached.set(key="foo_#email#",value=test,expiry="5000")>

foo_允许您为要放入memcached的键提供“命名空间”,这样可以更轻松地管理和避免关键冲突。