PHP Memcache 潜在问题?
我很可能会使用 MemCache 来缓存一些数据库结果。 由于我从未编写过缓存,因此我认为询问那些已经做过缓存的人是个好主意。我正在编写的系统可能在某个时间点并发运行脚本。这就是我打算做的事情:
- 我正在编写一个横幅交换系统。
- 有关横幅的信息存储在数据库中。
- 有不同的站点,具有不同的流量,加载将为这些横幅生成代码的 php 脚本。 (以便横幅显示在客户端的站点上)
- 当横幅第一次显示时 - 它会使用 memcache 进行缓存。
- 横幅的缓存寿命例如为 1 小时。
- 每小时都会更新缓存。
我在此任务中看到的潜在问题位于步骤 4 和 6。 例如,如果我们有 100 个流量较大的站点,则脚本可能会同时运行多个实例。如何保证缓存过期后会重新生成一次并且数据完好无损?
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:
- I'm writing a banner exchange system.
- The information about banners are stored in the database.
- 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)
- When a banner is being displayed for the first time - it get's cached with memcache.
- The banner has a cache life time for example 1 hour.
- 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于缺乏更好的词,我采用的缓存方法是“惰性”实现。也就是说,在检索某些内容之前,您不会缓存它,并希望有人会再次需要它。下面是该算法的伪代码:
只要您明智地使用缓存并了解并非所有信息都是相同的,这对于我们想要使用它的用途来说非常有效。例如,在假设的用户评论系统中,您不需要过期时间,因为只要新用户在文章上发表评论,您就可以简单地使缓存失效,以便下次加载评论时,它们被重新缓存。然而,一些信息(例如天气数据)应该有一个手动到期时间,因为您不依赖用户输入来更新数据。
就其价值而言,memcache 在集群环境中运行良好,您应该发现设置类似的东西并不难,因此这应该很容易扩展到您需要的任何内容。
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:
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.