search
HomeBackend DevelopmentPHP TutorialDetailed graphic explanation of PHP memory caching function memcached

Detailed graphic explanation of PHP memory caching function memcached

May 31, 2018 pm 02:11 PM
memcachedphpGraphics and text

This article mainly introduces the example of PHP memory caching function memcached. It briefly introduces memcached, which is a typical application of PHP to operate memcached. Friends in need can come and learn about it.

The following is a brief introduction to memcached. The application examples of the class have certain reference value, and interested friends can refer to them.

1. Introduction to memcached

On many occasions, we will hear the name memcached, but many students have only heard it and it is of no use. I have never seen it before or actually understood it, and I 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, which can be downloaded directly from the official website. memcached-1.1.12.tar.gz. 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
# make install

After the installation is complete, 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 and does not need to modify any configuration. File (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, The unit is M;

  • -l Set the monitoring IP address. If it is the local machine, you usually do not need to set this parameter;

  • - p sets the listening port, the default is 11211, so this parameter does not need to be set;

  • -u specifies the user. If you are 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. How memcached works

First of all, memcached runs in one or more servers as a daemon and accepts requests from clients at any time. For connection operations, the client can be written in various languages. Currently known client APIs include Perl/PHP/Python/Ruby/Java/C#/C and so on. 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.

5. How to use PHP as a memcached client

There are two ways to use PHP as a memcached client to call the memcached service for objects 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 php_memcache.dll in php.ini. comment character in front of it to make it available.

In addition, there is another way to avoid the trouble caused by expansion and recompilation, and that 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.

6. PHP memcached application example

First download memcached-client.php. After downloading memcached-client.php, you can use this file The class "memcached" in operates the memcached service. 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)

Write objects into memcached, $key is the unique identifier of the object, $val is the object data written, $exp is the expiration time in seconds, and the default is unlimited time;

get ($key)

Get object data from memcached through 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 the add() method. 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 how long to wait before deleting .

The following is a simple test code, which performs access operations on the object data with the identifier 'mykey':

<?php 
// 包含 memcached 类文件 
require_once(&#39;memcached-client.php&#39;); 
// 选项设置 
$options = array( 
 &#39;servers&#39; => array(&#39;192.168.1.1:11211&#39;), //memcached 服务的地址、端口,可用多个数组元素表示多个 memcached 服务 
 &#39;debug&#39; => true, //是否打开 debug 
 &#39;compress_threshold&#39; => 10240, //超过多少字节的数据时进行压缩 
 &#39;persistant&#39; => false //是否使用持久连接 
 ); 
// 创建 memcached 对象实例 
$mc = new memcached($options); 
// 设置此脚本使用的唯一标识符 
$key = &#39;mykey&#39;; 
// 往 memcached 中写入对象 
$mc->add($key, &#39;some random strings&#39;); 
$val = $mc->get($key); 
echo "n".str_pad(&#39;$mc->add() &#39;, 60, &#39;_&#39;)."n"; 
var_dump($val); 
// 替换已写入的对象数据值 
$mc->replace($key, array(&#39;some&#39;=>&#39;haha&#39;, &#39;array&#39;=>&#39;xxx&#39;)); 
$val = $mc->get($key); 
echo "n".str_pad(&#39;$mc->replace() &#39;, 60, &#39;_&#39;)."n"; 
var_dump($val); 
// 删除 memcached 中的对象 
$mc->delete($key); 
$val = $mc->get($key); 
echo "n".str_pad(&#39;$mc->delete() &#39;, 60, &#39;_&#39;)."n"; 
var_dump($val); 
?>

是不是很简单,在实际应用中,通常会把数据库查询的结果集保存到 memcached 中,下次访问时直接从 memcached 中获取,而不再做数据库查询操作,这样可以在很大程度上减轻数据库的负担。通常会将 SQL 语句 md5() 之后的值作为唯一标识符 key。下边是一个利用 memcached 来缓存数据库查询结果集的示例(此代码片段紧接上边的示例代码):

<?php 
$sql = &#39;SELECT * FROM users&#39;; 
$key = md5($sql); //memcached 对象标识符 
{ 
 // 在 memcached 中未获取到缓存数据,则使用数据库查询获取记录集。 
 echo "n".str_pad(&#39;Read datas from MySQL.&#39;, 60, &#39;_&#39;)."n"; 
 $conn = mysql_connect(&#39;localhost&#39;, &#39;test&#39;, &#39;test&#39;); 
 mysql_select_db(&#39;test&#39;); 
 $result = mysql_query($sql); 
 while ($row = mysql_fetch_object($result)) 
  $datas[] = $row; 
 // 将数据库中获取到的结果集数据保存到 memcached 中,以供下次访问时使用。 
 $mc->add($key, $datas); 
{ 
 echo "n".str_pad(&#39;Read datas from memcached.&#39;, 60, &#39;_&#39;)."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数据库操作mongodb的用法

PHP中in_array隐式转换实现步骤详解

PHP关于堆排序算法详解

The above is the detailed content of Detailed graphic explanation of PHP memory caching function memcached. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

How does using HTTPS affect session security?How does using HTTPS affect session security?Apr 22, 2025 pm 05:13 PM

HTTPS significantly improves the security of sessions by encrypting data transmission, preventing man-in-the-middle attacks and providing authentication. 1) Encrypted data transmission: HTTPS uses SSL/TLS protocol to encrypt data to ensure that the data is not stolen or tampered during transmission. 2) Prevent man-in-the-middle attacks: Through the SSL/TLS handshake process, the client verifies the server certificate to ensure the connection legitimacy. 3) Provide authentication: HTTPS ensures that the connection is a legitimate server and protects data integrity and confidentiality.

The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

See all articles

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 Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor