在PHP SESSION中缓存数据,还是每次都从db查询? [英] Cache data in PHP SESSION, or query from db each time?

查看:172
本文介绍了在PHP SESSION中缓存数据,还是每次都从db查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(A)缓存在$ _SESSION数组中的每个页面加载时使用的数据(更好)(更高效,更快,更安全等)(但仍在表中查询用于重新加载数据的标志)是否更好?新鲜),还是(B)每次都从数据库中加载它?

Is it "better" (more efficient, faster, more secure, etc) to (A) cache data that is used on every page load in the $_SESSION array (but still querying a table for a flag to reload the data fresh), or (B) to load it from the database each time?

我正在使用缓存方法(A),但是我担心有数百个用户,内存可能会成为问题?这只是简单的数据,例如名字,姓氏,生日等.

I'm using the cache method (A), but I'm worried that with hundreds of users, memory could become an issue? It's just simple data, like firstname, lastname, birthday, etc.

无论使用哪种方法,仍然有一个查询正在运行.有想法吗?

With either method, there's still a query being run. Thoughts?

推荐答案

如果您的数据在每个页面上都使用,并且对所有用户都是相同的,则我不会将其缓存在$ _SESSION中(这意味着具有不同的副本)每个用户的数据),但具有另一种机制,例如:

If your data is used on every pages, and is the same for all users, I wouldn't cache it in $_SESSION (which means having a different copy of that data for each user), but with another mecanism, like :

  • 文件
  • 在内存中,例如以APC(如果只有1台服务器)
  • 在内存中,例如使用memcached(如果您有多个服务器)
  • 如果您的数据需要较长的计算时间或需要获取多个数据库查询,则将其缓存在数据库中可能是另一种可能性(这将意味着仅要查询一次就可以取回查询,而计算量更少)


如果每个用户的数据都不相同((在您的情况下似乎是这种情况,因为您正在缓存名称,生日,...):


If your data is not the same for each user (which seems to be the case in your situation, as you are caching names, birthdates, ...) :

  • 我将确保只缓存必要的内容
  • 一旦要缓存的数据很少,将其放入会话中就可以了
  • 如果您确实有那么多用户,则可能会遇到其他一些可伸缩性问题,并且很可能会使用诸如memcached之类的东西;这意味着您将拥有其他缓存方式;-)

作为旁注:如果您要一遍又一遍地执行相同的查询,则DB服务器应自行对其进行缓存(对于MySQL,它将进入"

As a sidenote : if you are doing the same query over and over again, you DB server should cache it by itself (for MySQL, it would go into the "query cache") ; so, it would not be as bad as you think, I suppose -- even if not that much optimized ^^

这篇关于在PHP SESSION中缓存数据,还是每次都从db查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆