duanqianwei2485 2011-04-13 23:45
浏览 23
已采纳

PHP Memcache潜在的问题?

I'll most probably be using MemCache for caching some database results. As I haven't ever written and done caching I thought it would be a good idea to ask those of you who have already done it. The system I'm writing may have concurrency running scripts at some point of time. This is what I'm planning on doing:

  1. I'm writing a banner exchange system.
  2. The information about banners are stored in the database.
  3. There are different sites, with different traffic, loading a php script that would generate code for those banners. (so that the banners are displayed on the client's site)
  4. When a banner is being displayed for the first time - it get's cached with memcache.
  5. The banner has a cache life time for example 1 hour.
  6. Every hour the cache is renewed.

The potential problem I see in this task is at step 4 and 6. If we have for example 100 sites with big traffic it may happen that the script has a several instances running simultaneously. How could I guarantee that when the cache expires it'll get regenerated once and the data will be intact?

  • 写回答

1条回答 默认 最新

  • dongye8110 2011-04-14 00:16
    关注

    How could I guarantee that when the cache expires it'll get regenerated once and the data will be intact?

    The approach to caching I take is, for lack of a better word, a "lazy" implementation. That is, you don't cache something until you retrieve it once, with the hope that someone will need it again. Here's the pseudo code of what that algorithm would look like:

    // returns false if there is no value or the value is expired
    result = cache_check(key)
    
    if (!result)
    {
        result = fetch_from_db()
    
        // set it for next time, until it expires anyway
        cache_set(key, result, expiry)
    }
    

    This works pretty well for what we want to use it for, as long as you use the cache intelligently and understand that not all information is the same. For example, in a hypothetical user comment system, you don't need an expiry time because you can simply invalidate the cache whenever a new user posts a comment on an article, so the next time comments are loaded, they're recached. Some information however (weather data comes to mind) should get a manual expiry time since you're not relying on user input to update your data.

    For what its worth, memcache works well in a clustered environment and you should find that setting something like that up isn't hard to do, so this should scale pretty easily to whatever you need it to be.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器