简体   繁体   English

使用“主会话”进行站点范围的缓存

[英]Using 'master session' for site-wide cache

I've been wanted to add a caching feature to my websites which persist between multiple user sessions. 我一直想向网站添加一个缓存功能,该功能在多个用户会话之间保持不变。 The idea is to be able to store the result of frequently executed queries, or calculations which also don't change very often. 这个想法是为了能够存储频繁执行的查询或不经常更改的计算的结果。 My main use for this is when a user hits my website, a query runs to find the page they have requested. 我主要的用途是当用户访问我的网站时,会运行查询来查找他们请求的页面。 Pages change very infrequently so I'd like to cache this result for 2-4 hours for ever user so that query doesn't have to run over and over on every pageload for every user. 页面很少更改,因此我想为每个用户将该结果缓存2-4个小时,这样查询就不必为每个用户的每次页面加载都一遍又一遍地运行。

What I've made is a PHP Object which stores the current session_id and whenever a read or write is made to the cache object, it closes the session with session_write_close(), starts a new session with a hardcoded session_id reads/writes to/from this hardcoded 'master' session, and then reverts to the original session_id after session_write_close()ing the master session. 我所做的是一个存储当前session_id的PHP对象,每当对缓存对象进行读取或写入操作时,它将使用session_write_close()关闭该会话,并使用一个硬编码的session_id启动一个新的会话,以读取/写入此硬编码的“主”会话,然后在对主会话进行session_write_close()之后恢复为原始session_id。

Can anyone think of any issues with this approach? 有人能想到这种方法有什么问题吗? I wanted to avoid using anything overly sophisticated like memecache so I thought this was pretty simple, and it seems to work just fine! 我想避免使用任何过于复杂的功能(例如memecache),所以我认为这很简单,而且看起来还不错!

Thoughts and other ideas for approaches would be appreciated! 对于方法的想法和其他想法将不胜感激!

This solution sounds more complicated then simply using Memcache. 与仅使用Memcache相比,此解决方案听起来更复杂。

The main issue I have with this solution is that you are using Session to basically store cache files. 此解决方案的主要问题是您正在使用Session来基本上存储缓存文件。 PHP by default stores session in files and you are closing and opening sessions unnecessary. 默认情况下,PHP将会话存储在文件中,您无需关闭和打开会话。 Here is a simpler way for you to accomplish exactly the same with better performance: 这是一种更简单的方法,可让您以更好的性能完成任务:

  1. Check to see if your cache file is older then 2 hours using filemtime() : 使用filemtime()检查您的缓存文件是否旧于2个小时:

     if(filemtime($cache_file) > time()-3600*2) 
  2. If older you create your PHP Cache object and write it to the cache file using file_put_contents() and serialize() : 如果较旧,则创建PHP缓存对象,然后使用file_put_contents()serialize()将其写入缓存文件:

     file_put_contents($cache_file, serialize($cache_object)) 
  3. If the file is younger then 2 hours then retrieve the PHP Cache object using file_get_contents() and unserialize() 如果文件太小,则需要2个小时,然后使用file_get_contents()unserialize()检索PHP Cache对象

     $cache_object = unserialize(file_get_contents($cache_file)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM