


PHP memory cache acceleration function memcached installation and usage_PHP tutorial
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 clients such as PHP 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 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':
// Contains memcached class files
require_once('memcached-client.php');
// Option settings
$options = array(
'servers' => array('192.168.1.1:11211'), //The address and port of the memcached service. Multiple array elements can be used to represent multiple memcached services
'debug' => true, //Whether debug is turned on
' compress_threshold' => 10240, //Compress when the data exceeds the number of bytes
'persistant' => false //Whether to use persistent connections
);
//Create memcached object instance
$mc = new memcached($options);
//Set the unique identifier used by this script
$key = 'mykey';
//Write the object into memcached
$mc ->add($key, 'some random strings');
$val = $mc->get($key);
echo "n".str_pad('$mc->add( ) ', 60, '_')."n";
var_dump($val);
// Replace the written object data value
$mc->replace($key, array ('some'=>'haha', 'array'=>'xxx'));
$val = $mc->get($key);
echo "n".str_pad( '$mc->replace() ', 60, '_')."n";
var_dump($val);
// Delete objects in 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 practical applications, the result set of the database query is usually saved to memcached. , get it directly from memcached the next time you access it, instead of doing database query operations, which 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. The following is an example of using memcached to cache the database query result set (this code snippet follows the sample code above):
$sql = 'SELECT * FROM users';
$key = md5($sql); //memcached object identifier
{
// was not obtained in memcached To cache data, use a database query to obtain the record set.
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;
//Save the result set data obtained from the database to memcached for use during the next access.
$mc->add($key, $datas);
{
echo "n".str_pad('Read datas from memcached.', 60, '_')."n";
}
var_dump($datas);
?>
It can be seen that after using memcached, database connections and query operations can be reduced, and the database load is reduced. The script The running speed has also been improved. I have written an article before called "PHP implements multi-server sharing of SESSION data". The SESSION in the article is saved in a database. When the number of concurrent accesses is large, the load on the server will be very large, and the maximum connection of MySQL will often be exceeded. Number, using memcached, we can solve this problem very well. The working principle is as follows:
When the user accesses the webpage, check whether there is the SESSION data of the current user in memcached, and use session_id() as the unique identifier; if the data exists, Then return directly. If it does not exist, connect to the database again, obtain the SESSION data, and save this data to memcached for next use;
When the current PHP operation ends (or session_write_close() is used), it will Call the My_Sess::write() method to write data to the database. In this case, there will still be database operations every time. This method also needs to be optimized. Use a global variable to record the SESSION data when the user enters the page, and then compare this data in the write() method to see if it is the same as the SESSION data you want to write. If they are different, connect to the database and write it to the database. At the same time, add the corresponding data in memcached. Object deletion, if they are the same, it means that the SESSION data has not changed, then it can be returned directly without any operation;
So how to solve the user SESSION expiration time? Remember that memcached’s add() method has an expiration time parameter $exp? Just set this parameter value to be less than the maximum survival time of SESSION. In addition, don’t forget to extend the SESSION duration for those users who are always online. This can be solved in the write() method. By judging the time, the database data will be updated if the conditions are met.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.