在分析应用程序时,我发现会话启动大约占请求总时间的一半(一个请求总共大约4秒)。由于并非所有存储的对象都用于用户的每个请求,因此我尝试通过选择性地恢复请求所需的对象来提高应用程序的响应性。为此,我将对象序列化为单独的文件,并仅取消序列化所需的对象。这一变化实际上破坏了应用程序,因为序列化/反序列化消耗了大量内存(和运行时间)。令我惊讶的是,会话处理程序可以在更短的时间内序列化和反序列化所有对象,并且比我尝试只处理一个子集所消耗的内存更少。我相信这可能是因为所有序列化的对象数据都加载到了内存中,但我不确定。
下面是序列化和反序列化我使用过的对象的代码:
将序列化对象写入文件的代码:
public static function writeClose() {
foreach (self::$activeRegistries as $registryName=>$registry) {
if (isset($_SESSION["filemap"]) && isset($_SESSION["filemap"]["registries"]) && isset($_SESSION["filemap"]["registries"][$registryName])) {
$path = $_SESSION["filemap"]["registries"][$registryName];
if (file_put_contents($path, serialize($registry)) === false) {
throw new repositoryException("Exception while writing the '$registryName' registry to storage");
}
} else {
throw new repositoryException("Could not find the file path for the '$registryName' registry");
}
}
}检索序列化对象的代码:
private static function getRegistry($registryName) {
// First check to see if the registry is already active in this request
if (isset(self::$activeRegistries[$registryName])) {
$registry = self::$activeRegistries[$registryName];
} else {
// The registry is not active, so see if it is stored for the session
if (isset($_SESSION["filemap"]) && isset($_SESSION["filemap"]) && isset($_SESSION["filemap"]["registries"][$registryName])) {
$filePath = $_SESSION["filemap"]["registries"][$registryName];
if (file_exists($filePath)) {
$registry = unserialize(file_get_contents($filePath));
self::$activeRegistries[$registryName] = $registry;
} else {
throw new repositoryException("Exception while getting serialized object for registry '$registryName'");
}
} else {
// The registry is not saved in the session, so create a new one
$registry = self::createRegistry($registryName);
$filePath = "/tmp/" . session_id() . $registryName;
$_SESSION["filemap"]["registries"][$registryName] = $filePath;
self::$activeRegistries[$registryName] = $registry;
}
}
return $registry;
}发布于 2013-08-08 03:45:45
您可以通过更改会话的存储位置来加速现有的基于会话的实现。默认情况下,会话数据被写入服务器上的文件,然后通过浏览器cookie进行关联。如果您的会话包含大量数据,则您看到的时间可能是物理驱动器的寻道时间和读取时间。
但是,PHP支持几种会话存储方法。我建议尝试MemCached选项:http://php.net/manual/en/memcached.sessions.php
session.save_handler = memcached
session.save_path = "localhost:11211"当然,您需要安装MemCached。
https://stackoverflow.com/questions/17904051
复制相似问题