memcached PHP semaphore & cache expiration handling

There are a lot of different ways that people use memcached and PHP. The most common of which is probably your basic set and get to cache data from your database.

  1. span class=”st0″>"mykey"

But what if the query that’s going to hit the database is pretty intensive and you don’t want more than one user to hit the db at a time? That’s easily handling via a semaphore lock.

  1. span class=”st0″>"mykey"// check to see if someone has already set the lock
  2. ‘_qry_lock’// loop until you find that the lock has been released.  that implies that the query has finished
  3. // you may only want to wait for a specified period of time.
  4.                 // one second is usually sufficient since your goal is to always have sub-second response time
  5.                 // if you query takes more than 1 second, you should consider "warming" your cached data via a cron job
  6. // you really want this to be a fraction of a second so the user waits as little as possible
  7.                 // for the simplicity of example, I’m using the sleep function.
  8. ‘_qry_lock’);
  9.             }
  10.             // if the loop is completed, that either means the user waited for too long
  11.             // or that the lock has been removed.  try to get the cached data again; it should exist now
  12. // set a lock for 2 seconds
  13. ‘_qry_lock’// don’t forget to remove the lock
  14. ‘_qry_lock’

More below the break –> Read More…

Posted under mysql, PHP, Tips & Tricks, Web Development

This post was written by Michael Tougeron on January 11, 2008

Tags: , ,