Search code examples
coldfusionmemcachedcoldfusion-9

Using Memcached with Coldfusion


I am trying to use memcached for the first time but I have a few questions when it comes to queries with dynamic variables.

This is a sample of my code so far. I got everything working but if you see any mistakes on my code please let me know.

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

Now, do i have to set a key for every possible outcome of the query? (which in my case would be a few hundred keys to cover all possible outcomes) My understanding is that memcached saves the value to a key after the first request and after that you get the output without db calls. If I use memcached in my case would it just be a waste of code since each query would be different based on the user's choice?

Also, how do you update the values in cache in case the output changes? Is this something that I would have to do manually? My database get 100's of transactions daily, a select * from contacts at 10 am will not have the same output at 5pm


Solution

  • The idea behind caching (in this case) is that you first check memcached, and if the key exists, you get the data from the cache. If it doesn't exist, you go to the database, get the data, stick it in memcached, then return it to the user.

    For your use case here, you want a unique key for each unique record set you're returning. Take your example. If email address is the unique key you are using to identify a record set, then use that as the key in memcached. Pseudo-code:

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

    foo_ lets you provide a "namespace" for the keys you are putting into memcached, which makes it easier to manage and avoid key collisions.