1. Introduction to memcached On many occasions, we will hear the name memcached, but many students have only heard of it and have not used it or actually understood it. They only know that it is a very good thing. Here is a brief introduction: memcached is an efficient and fast distributed memory object caching system, mainly used to accelerate WEB dynamic applications. 2. Memcached installation The first step is to download memcached. The latest version is 1.1.12. You can download memcached-1.1.12.tar.gz directly from the official website. In addition, memcached uses libevent, and I downloaded libevent-1.1a.tar.gz. The next step is to unpack, compile and install libevent-1.1a.tar.gz and memcached-1.1.12.tar.gz respectively: # tar -xzf libevent-1.1a.tar.gz
# cd libevent- 1.1a
# ./configure --prefix=/usr
# make
# make install
# cd ..
# tar -xzf memcached-1.1.12.tar.gz
# cd memcached-1.1.12
# ./configure --prefix=/usr
# make
# After make install is installed, memcached should be in /usr/bin/memcached. 3. Run the memcached daemon. Running the memcached daemon is very simple. It only requires a command line. There is no need to modify any configuration files (there is no configuration file for you to modify): /usr/bin/memcached -d -m 128 -l 192.168.1.1 -p 11211 -u httpd parameter explanation: -d runs memcached in daemon mode;
-m sets the memory size that memcached can use, in M;
-l sets the listening IP Address, if it is the local machine, this parameter usually does not need to be set;
-p sets the listening port, the default is 11211, so this parameter does not need to be set;
-u specifies the user, if it is currently root , you need to use this parameter to specify the user. Of course, there are other parameters that can be used. You can see them by running man memcached. 4. The working principle of memcached: First, memcached runs in one or more servers as a daemon and accepts client connection operations at any time. The client can be written in various languages. Currently known client APIs include Perl/PHP/ Python/Ruby/Java/C#/C etc. After PHP and other clients establish a connection with the memcached service, the next thing is to access objects. Each accessed object has a unique identifier key. Access operations are performed through this key and saved to memcached. The objects in are actually placed in memory, not stored in cache files, which is why memcached can be so efficient and fast. Note that these objects are not persistent, and the data inside will be lost after the service is stopped. 3. How to use PHP as a memcached client. There are two ways to use PHP as a memcached client to call memcached services for object access operations. First, PHP has an extension called memcache. When compiling under Linux, you need to bring the –enable-memcache[=DIR] option. Under Windows, remove the comment in front of php_memcache.dll in php.ini to make it available. In addition, there is another way to avoid the trouble caused by expansion and recompilation, which is to use php-memcached-client directly. This article chooses the second method. Although the efficiency will be slightly worse than that of the extension library, it is not a big problem. 4. PHP memcached application example First download memcached-client.php. After downloading memcached-client.php, you can operate the memcached service through the class "memcached" in this file. In fact, the code call is very simple. The main methods used are add(), get(), replace() and delete(). The method description is as follows: add ($key, $val, $exp = 0)
Go to Write objects in memcached. $key is the unique identifier of the object. $val is the written object data. $exp is the expiration time in seconds. The default is unlimited time; get ($key)
From memcached Obtain the object data from the object's unique identifier $key; replace ($key, $value, $exp=0)
Use $value to replace the object content with the identifier $key in memcached. The parameters are the same as add( ) method is the same, it will only work if the $key object exists; delete ($key, $time = 0)
Delete the object with the identifier $key in memcached, $time is an optional parameter, indicating deletion How long to wait before. The following is a simple test code that accesses object data with the identifier 'mykey':
// 包含 memcached 类文件 require_once('memcached-client.php'); // 选项设置 $options = array( 'servers' => array('192.168.1.1:11211'), //memcached 服务的地址、端口,可用多个数组元素表示多个 memcached 服务 'debug' => true, //是否打开 debug 'compress_threshold' => 10240, //超过多少字节的数据时进行压缩 'persistant' => false //是否使用持久连接 ); // 创建 memcached 对象实例 $mc = new memcached($options); // 设置此脚本使用的唯一标识符 $key = 'mykey'; // 往 memcached 中写入对象 $mc->add($key, 'some random strings'); $val = $mc->get($key); echo "n".str_pad('$mc->add() ', 60, '_')."n"; var_dump($val); // 替换已写入的对象数据值 $mc->replace($key, array('some'=>'haha', 'array'=>'xxx')); $val = $mc->get($key); echo "n".str_pad('$mc->replace() ', 60, '_')."n"; var_dump($val); // 删除 memcached 中的对象 $mc->delete($key); $val = $mc->get($key); echo "n".str_pad('$mc->delete() ', 60, '_')."n"; var_dump($val); ?>
Isn't it very simple? In actual applications, the result set of a database query is usually Save it to memcached and obtain it directly from memcached the next time you access it, instead of doing database query operations. This can reduce the burden on the database to a great extent. Usually the value after the SQL statement md5() is used as the unique identifier key. Below is an example of using memcached to cache a database query result set (this code snippet follows the sample code above):
$sql = 'SELECT * FROM users'; $key = md5($sql); //memcached 对象标识符 { // 在 memcached 中未获取到缓存数据,则使用数据库查询获取记录集。 echo "n".str_pad('Read datas from MySQL.', 60, '_')."n"; $conn = mysql_connect('localhost', 'test', 'test'); mysql_select_db('test'); $result = mysql_query($sql); while ($row = mysql_fetch_object($result)) $datas[] = $row; // 将数据库中获取到的结果集数据保存到 memcached 中,以供下次访问时使用。 $mc->add($key, $datas); { echo "n".str_pad('Read datas from memcached.', 60, '_')."n"; } var_dump($datas); ?>
可以看出,使用 memcached 之后,可以减少数据库连接、查询操作,数据库负载下来了,脚本的运行速度也提高了。之前我曾经写过一篇名为《PHP 实现多服务器共享 SESSION 数据》文章,文中的 SESSION 是使用数据库保存的,在并发访问量大的时候,服务器的负载会很大,经常会超出 MySQL 最大连接数,利用 memcached,我们可以很好地解决这个问题,工作原理如下:
用户访问网页时,查看 memcached 中是否有当前用户的 SESSION 数据,使用 session_id() 作为唯一标识符;如果数据存在,则直接返回,如果不存在,再进行数据库连接,获取 SESSION 数据,并将此数据保存到 memcached 中,供下次使用;
当前的 PHP 运行结束(或使用了 session_write_close())时,会调用 My_Sess::write() 方法,将数据写入数据库,这样的话,每次仍然会有数据库操作,对于这个方法,也需要进行优化。使用一个全局变量,记录用户进入页面时的 SESSION 数据,然后在 write() 方法内比较此数据与想要写入的 SESSION 数据是否相同,不同才进行数据库连接、写入数据库,同时将 memcached 中对应的对象删除,如果相同的话,则表示 SESSION 数据未改变,那么就可以不做任何操作,直接返回了;
那么用户 SESSION 过期时间怎么解决呢?记得 memcached 的 add() 方法有个过期时间参数 $exp 吗?把这个参数值设置成小于 SESSION 最大存活时间即可。另外别忘了给那些一直在线的用户延续 SESSION 时长,这个可以在 write() 方法中解决,通过判断时间,符合条件则更新数据库数据。
更多PHP 内存缓存加速功能memcached安装与用法相关文章请关注PHP中文网!