search
HomeBackend DevelopmentPHP TutorialMemcache introductory tutorial Memcache php caching technology_PHP tutorial

Memcache introductory tutorial Memcache php caching technology_PHP tutorial

Jul 20, 2016 am 11:07 AM
memcachephpGetting Started Tutorialtechnologyyeswhat isofcacheproject

What is Memcache
Memcache is a project of danga.com. It was first used to serve LiveJournal. Currently, many people around the world use this caching project to build their own large-load websites to share the pressure of database tutorials.
It can handle any number of connections and uses non-blocking network IO. Since its working mechanism is to open up a space in the memory and then create a HashTable, Memcached manages these HashTables by itself.
Memcache official website: http://www.danga.com/memcached. For more detailed information, you can come here to learn

Why are there two names: Memcache and memcached?
Actually, Memcache is the name of this project, and memcached is the name of its main program file on the server side. You know what I mean~~~~. One is the project name, and the other is the main program file name. I saw many people on the Internet who didn’t understand, so they used them interchangeably.

Memcache installation
is divided into two processes: memcache server installation and memcached client installation.
The so-called server-side installation is to install Memcache on the server (usually a Linux system) to store data
The so-called client-side installation refers to the PHP tutorial (or other programs, Memcache also has other good API interfaces) To use the functions provided by Memcache on the server side, you need to add extensions to PHP.

PHP’s Memcache

Copy the code as follows:
//Connection

$mem = new Memcache;
$mem ->connect("192.168.0.200", 12000);

//Save data

$mem->set('key1', 'This is first value', 0, 60);
$val = $mem->get('key1');
echo "Get key1 value: " . $val ."
";

//Replace data

$mem->replace('key1', 'This is replace value', 0, 60);
$val = $mem->get('key1') ;
echo "Get key1 value: " . $val . "
";

//Save the array

$arr = array('aaa', ' bbb', 'ccc', 'ddd');
$mem->set('key2', $arr, 0, 60);
$val2 = $mem->get('key2' );
echo "Get key2 value: ";
print_r($val2);
echo "
";

//Delete data

$mem->delete('key1');
$val = $mem->get('key1');
echo "Get key1 value: " . $val . "
";

//Clear all data

$mem->flush();
$val2 = $mem->get('key2');
echo "Get key2 value: ";
print_r($val2);
echo "
";

//Close the connection
$mem->close ();
?>

If normal, the browser will output:

Get key1 value: This is first value
Get key1 value: This is replace value
Get key2 value: Array ( [0] => aaa [1] => bbb [2] => ccc [3] => ddd )
Get key1 value:
Get key2 value :

Program code analysis

Initialize a Memcache object:

$mem = new Memcache;

Connect to our Memcache server, first The first parameter is the IP address of the server, which can also be the host name. The second parameter is the open port of Memcache:

$mem->connect("192.168.0.200", 12000);

Save a data to the Memcache server. The first parameter is the key of the data, used to locate a data. The second parameter is the content of the data that needs to be saved. Here is a string. The third parameter is a mark. , generally set to 0 or MEMCACHE_COMPRESSED. The fourth parameter is the validity period of the data, which means that the data is valid within this time. If this time passes, the data will be cleared by the Memcache server. The unit is seconds. If set to 0, it will be valid forever. We set 60 here, which is valid for one minute:
$mem->set('key1', 'This is first value', 0, 60);

Get a piece of data from the Memcache server. It has only one parameter, which is the key to get the data. Here is the key1 set in the previous step. Now after getting this data, output the output:

$val = $mem->get('key1′);
echo "Get key1 value: " . $val;

Now use the replace method to replace the value of key1 above. The parameters of the replace method are as follows set is the same, but the first parameter key1 must be the key to replace the data content. The final output is:

$mem->replace('key1′, 'This is replace value', 0 , 60);
$val = $mem->get('key1′);
echo "Get key1 value: " . $val;

Similarly, Memcache can also save arrays Yes, the following is to save an array on Memcache, then get it back and output it

$arr = array('aaa', 'bbb', 'ccc', 'ddd');
$mem->set('key2′, $arr, 0, 60);
$val2 = $mem->get('key2′);
print_r($val2);

Now delete a data, use the delte interface, the parameter is a key, and then you can put the Memcache server The data of this key is deleted, and there is no result in the final output

$mem->delete('key1′);
$val = $mem->get('key1′);
echo "Get key1 value: " . $val . "
";

Finally, we clear all the data saved on the Memcache server, and we will find that the data is gone, and finally output key2 The data is empty, and finally the connection is closed

$mem->flush();
$val2 = $mem->get('key2′);
echo "Get key2 value: ";
print_r($val2);
echo "
";

Use of Memcache
Websites that use Memcache generally have relatively large traffic. In order to alleviate the problem of database Pressure, let Memcache serve as a cache area to save part of the information in the memory, so that it can be accessed quickly on the front end. So the general focus is on how to share database pressure and distribute it. After all, the memory capacity of a single Memcache is limited. I simply put forward my personal opinions here. I have not practiced them and should only be used as a reference.

Distributed application
Memcache originally supports distributed, but our client has been slightly modified to provide better support. Our keys can be encapsulated appropriately and regularly. For example, for a user-based website, each user has a User ID, so it can be extracted and accessed according to a fixed ID. For example, users starting with 1 are stored in the first On one Memcache server, the data of users starting with 2 is stored on the second Memcache server. The access data is first converted and accessed according to the User ID.

But this has the disadvantage that you need to judge the User ID. If the business is inconsistent, or other types of applications may not be so suitable, you can consider it based on your actual business, or think about something more suitable. method.

Reduce database pressure
This is quite important. All data are basically stored in the database. Frequent access to the database each time results in a huge decline in database performance and the inability to service updates at the same time. Many users, such as MySQL, lock tables very frequently, so let Memcache share the pressure on the database. We need a way to change the current architecture in a way that is relatively small and does not require large-scale changes to the front end.

A simple method I am considering:
The back-end database operation module extracts all Select operations (regardless of update/delete/insert), and then calculates the corresponding hash algorithm on the corresponding SQL Get a hash data key (such as MD5 or SHA), and then use this key to find the data in Memcache. If the data does not exist, it means that it has not been written to the cache, then extract the data from the database. One is an array class. format, and then set the data into Memcache. The key is the hash value of this SQL, and then set an expiration time accordingly, such as one hour. Then the data in one hour will be extracted from the cache, effectively reducing the pressure on the database. . The disadvantage is that the data is not real-time. When the data is modified, it cannot be displayed on the front end in real time, and it may also occupy a large amount of memory. After all, the amount of data selected each time may be huge. This is a factor that needs to be considered.

Security of Memcache
Our above Memcache server is directly connected through the client and operates directly without any verification process. In this way, if the server is directly exposed to the Internet, it is more dangerous and light. Then the data leakage is viewed by other unrelated people, or worse, the server is invaded, because Mecache is running with root privileges, and there may be some unknown bugs or buffer overflows in it. These are unknown to us, so they are dangerous. Sex is predictable. For the sake of security, I would like to make two suggestions to prevent hacker intrusion or data leakage.

Intranet access
It is best to use intranet access between two servers, usually between the Web server and the Memcache server. Common servers have two network cards, one pointing to the Internet and one pointing to the intranet. Then let the web server access the Memcache server through the intranet network card. When our Memcache server is started, it monitors the IP address and IP address of the intranet. Ports and intranet access can effectively prevent other illegal access.
# memcached -d -m 1024 -u root -l 192.168.0.200 -p 11211 -c 1024 -P /tmp/memcached.pid
The Memcache server is set to monitor the IP of 192.168.0.200 through the intranet Port 11211, occupies 1024MB of memory, and allows a maximum of 1024 concurrent connections

Set up a firewall
A firewall is a simple and effective way. If both servers are connected to the Internet and you need to access Memcache through the external IP, you can consider using a firewall or proxy program to filter out illegal access.
Generally, under Linux, we can use iptables or ipfw under FreeBSD to specify some rules to prevent some illegal access. For example, we can set up to only allow our web server to access our Memcache server, while blocking other access.

# iptables -F
# iptables -P INPUT DROP
# iptables -A INPUT -p tcp -s 192.168.0.2 –dport 11211 -j ACCEPT
# iptables -A INPUT - p udp -s 192.168.0.2 –dport 11211 -j ACCEPT

The above iptables rule only allows the 192.168.0.2 web server to access the Memcache server, which can effectively prevent some illegal access. Correspondingly, you can also add some other rules to enhance security. This can be done according to your own needs.


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/444929.htmlTechArticleWhat is Memcache? Memcache is a project of danga.com. It was first used to serve LiveJournal and is currently used by many around the world. People use this caching project to build their own high-load websites to split...
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
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.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

Dreamweaver CS6

Dreamweaver CS6

Visual web 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.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor