Home Backend Development PHP Tutorial (转)PHP缓存的兑现

(转)PHP缓存的兑现

Jun 13, 2016 pm 01:19 PM
file mysql records sql

(转)PHP缓存的实现

SQL查询缓存

适合读者

本教程适合于那些对缓存SQL查询以减少数据库连接与执行的负载、提高脚本性能感兴趣的PHP程序员。

概述

许多站点使用数据库作为站点数据存储的容器。数据库包含了产器信息、目录结构、文章或者留言本,有些数据很可能是完全静态的,这些将会从一个缓存系统中得到的极大好处。

这样一个系统通过把SQL查询的结果缓存到系统的一个文件中存储,从而阻止连接数据库,构造查询与取得返回结果而提高了响应时间。

有些系统数据库并不是放在WEB服务器上的,这样需要一个远程连接(TCP或者其它类似的),或者从数据库中获取大量的数据,这样你得忍受更多时间,这决定于系统响应时间与资源利用。

前提

本教程使用MySQL作为数据库。你需要安装MySQL(www.mysql.com下载是有效的)和激活PHP MYSQL扩展(默认情况是激活的)。

由于要查询数据库,你需要知识一些SQL(结构化查询语言)的基本常识。

缓存SQL查询结果

为什么要缓存查询结果?

缓存查询结果能极大地改进脚本执行时间和资源需求。

缓存SQL查询结果也允许你通过后期处理数据。如果你用文件缓存去存储全部脚本的输出结果(HTML输出),这样可能是行不通的。

当你执行一个SQL查询时,点典的处理过程是:

l        连接数据库

l        准备SQL查询

l        发送查询到数据库

l        取得返回结果

l        关闭数据库连接

以上方法非常占用资源并且相反的影响了脚本的性能。只能通过取得的大量返回数据和数据库服务器的位置这二个要素来相互协调。尽管持续连接可以改进连接数据库时的负载,但非常耗费内存资源,如果获取的是大量的数据,那么存储的全部时间会非常短暂。

创建一条SQL查询:

SQL(结构化查询语言)查询被用作操作数据库及它内容的接口。SQL可用于定义和编辑表的结构,插入数据到表,更新或删除表中的信息。

SQL是用于与数据通讯的语言,在大多数PHP数据库扩展(MySQL,ODBC,Oracle等)通过传递SQL查询到数据库中来管理整个过程。

本教程中,仅仅用select语言来获取数据库中的数据。这些数据将被缓存,之后将用作数据源。

决定什么时候更新缓存:

根据程序的需要,缓存可以采取多种形式。最常见的3种方式是:

l        时间触发缓存(过期的时间戳)

l        内容改变触发缓存(发现数据改变后,相应地更新缓存)

l        人工触发缓存(人工的方式告知系统信息超期并且强制产生新的缓存)

你的缓存需求可能是以上原理的一个或多个的综合。本教程将讨论时间触发方式。然而,在一个全面的缓存机制中,3种方式的综合将被使用。

缓存结果:

基本的缓存是用PHP的两个函数serialize()和unserialize()(译注:这二个函数分别代表序列化与反序列化)。

函数serialize()用于存储PHP的值,它能保证不失去这些值的类型和结构。

事实上,PHP的session扩展是用序列化过的变量,把session变量($_SESSION)存储在系统的一个文件中。

函数unserialize()与以上操作相反并且使序列化过的字符串返回到它原来的结构和数据内容。

在本例中,以一个电子商务商店为例。商店有2个基本表,categories和products(此处为原始数据库表名).product表可能每天都在变化,categories仍然是不变静止的。

要显示产品,你可以用一个输出缓存脚本来存储输出的HTML结果到一个文件中。然而categories表可能需要后期处理。例如,所有的目录通过变量category_id(通过$_REQUEST['category_id']来取得)被显示,你可能希望高亮当前被选择的目录。

表categories结构

Field

Type 

Key

Extra

category_id

category_name

category_description

int(10) unsigned

varchar(255)

text

PRI

auto_incremen

 

 

在本例中,通过时间触发缓存技术被运用,设定一段时间后让其缓存SQL输出过期。在此特殊的例子中,定一段时间为24小时。

序列化例子:

l        连接数据库

l        执行查询

l        取得所有结果构成一个数组以便后面你可以访问

l        序列化数组

l        保存序列化过的数组到文件中

$file = 'sql_cache.txt';

$link = mysql_connect('localhost','username','password')

    or die (mysql_error());

mysql_select_db('shop')

    or die (mysql_error());

/* 构造SQL查询 */

$query = "SELECT * FROM categories";

$result = mysql_query($query)

    or die (mysql_error());

while ($record = mysql_fetch_array($result) )

{

    $records[] = $record;

}

$OUTPUT = serialize($records);

$fp = fopen($file,"w"); // 以写权限的方式打开文件

fputs($fp, $OUTPUT);

fclose($fp);

查看sql_cache.txt文件,里面的内容可能类似这样的:

a:1:{i:0;a:6:{i:0;s:1:"1";s:11:"category_id";s:1:"1";i:1;s:9:"Computers";s:13:"category_name";s:9:

"Computers" ;i:2;s:25:"Description for computers";s:20:"category_description"

;s:25:"Description for computers";}}

这个输出是它的变量和类型的内部表现形式。假若你用mysql_fetch_array()函数返回数字索引的数组和一个关联的数组(这就是为什么数据看起来像是发生了两次),一个是数字索引,另一个是字符串索引。

使用缓存:

要用缓存,你需要用函数unserialize()来使数据还原成原始格式与类型。

你可以用file_get_contents()这个函数来读取sql_cache.txt文件的内容,把它赋给一个变量。

请注意:这个函数在PHP4.3.0及以上版本有效。若你使用的是一个老版本的PHP,一个简单的方法是用file()函数(读整个文件到一个数组,每行变成一个数组)。implode()函数用于把数组的各元素连接成一个字符串然后使用unserialize()反序列化。

// file_get_contents() 适合于for PHP < 4.3.0

$file = 'sql_cache.txt';

$records = unserialize(implode('',file($file)));

现在你可以通过$records数组并且取得原始查询的数据:

foreach ($records as $id=>$row) {

    print $row['category_name']."<br>";

}

注意$records是数组(一个包含了查询结果的数字索引列――每行是一个数字和一个字符串...真是混乱)的一排。

把它们放在一块:

基于本例子中的时间来决定是否缓存。如果文件修改的时间戳比当前时间戳减去过期时间戳大,那么就用缓存,否则更新缓存。

l        检查文件是否存在并且时间戳小于设置的过期时间

l        获取存储在缓存文件中的记录或者更新缓存文件

$file = 'sql_cache.txt';

$expire = 86400; // 24 小时 (单位:秒)

if (file_exists($file) && 

filemtime($file) > (time() - $expire))

{

    // 取得缓存中的记录

    $records = unserialize(file_get_contents($file));

} else {

    // 通过 serialize() 函数创建缓存

}

附加其它可能的:

l        把缓存结果存储在共享内存中以获取更快的速度

l        增加一个功能随机地运行SQL查询并且检查是否输出与缓存输出一致。如果不一致,则更新缓存(本函数运行次数的概率可以定为1/100)。通过哈希算法(如MD5())可以协助判断字符串或者文件是否改变。

l        增加一个管理员的功能,人工的删除这个缓存文件,以强制更新缓存(如file_exists()函数返回false时)。你可以用函数unlink()删除文件。

脚本:

$file = 'sql_cache.txt';

$expire = 86400; // 24 小时

if (file_exists($file) &&

    filemtime($file) > (time() - $expire)) {

    $records = unserialize(file_get_contents($file));

} else {

    $link = mysql_connect('localhost','username','password')

        or die (mysql_error());

    mysql_select_db('shop')

        or die (mysql_error());

    /* 构造SQL查询 */

    $query = "SELECT * FROM categories";

    $result = mysql_query($query)

        or die (mysql_error());

    while ($record = mysql_fetch_array($result) ) {

        $records[] = $record;

    }

    $OUTPUT = serialize($records);

    $fp = fopen($file,"w");

    fputs($fp, $OUTPUT);

    fclose($fp);

} // end else

 

// 查询结果在数组 $records 中

foreach ($records as $id=>$row) {

    if ($row['category_id'] == $_REQUEST['category_id']) {

        // 被选择的目录显示粗体字

        print '<B>'.$row['category_name'].'</B><BR>';

    } else {

        // 其它目录显示用常规字体

        print $row['category_name'].'<br>';

    }

} // end foreach

关于作者

Ori Staub是专注于研究基于WEB解决方案的中级系统分析员,开发者和顾问。可以通过电子邮件os@zucker-staub.com联系他。

原文地址:http://www.zend.com/zend/tut/tutorial-staub2.php

翻译的不是太好,请见谅!

本文由arcow翻译。email:phpers+csdn@gmail.com
Copy after login
?
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Explain the purpose of foreign keys in MySQL. Explain the purpose of foreign keys in MySQL. Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

Compare and contrast MySQL and MariaDB. Compare and contrast MySQL and MariaDB. Apr 26, 2025 am 12:08 AM

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

SQL vs. MySQL: Clarifying the Relationship Between the Two SQL vs. MySQL: Clarifying the Relationship Between the Two Apr 24, 2025 am 12:02 AM

SQL is a standard language for managing relational databases, while MySQL is a database management system that uses SQL. SQL defines ways to interact with a database, including CRUD operations, while MySQL implements the SQL standard and provides additional features such as stored procedures and triggers.

MySQL: The Database, phpMyAdmin: The Management Interface MySQL: The Database, phpMyAdmin: The Management Interface Apr 29, 2025 am 12:44 AM

MySQL and phpMyAdmin can be effectively managed through the following steps: 1. Create and delete database: Just click in phpMyAdmin to complete. 2. Manage tables: You can create tables, modify structures, and add indexes. 3. Data operation: Supports inserting, updating, deleting data and executing SQL queries. 4. Import and export data: Supports SQL, CSV, XML and other formats. 5. Optimization and monitoring: Use the OPTIMIZETABLE command to optimize tables and use query analyzers and monitoring tools to solve performance problems.

How to safely store JavaScript objects containing functions and regular expressions to a database and restore? How to safely store JavaScript objects containing functions and regular expressions to a database and restore? Apr 19, 2025 pm 11:09 PM

Safely handle functions and regular expressions in JSON In front-end development, JavaScript is often required...

Steps to add and delete fields to MySQL tables Steps to add and delete fields to MySQL tables Apr 29, 2025 pm 04:15 PM

In MySQL, add fields using ALTERTABLEtable_nameADDCOLUMNnew_columnVARCHAR(255)AFTERexisting_column, delete fields using ALTERTABLEtable_nameDROPCOLUMNcolumn_to_drop. When adding fields, you need to specify a location to optimize query performance and data structure; before deleting fields, you need to confirm that the operation is irreversible; modifying table structure using online DDL, backup data, test environment, and low-load time periods is performance optimization and best practice.

See all articles