Table of Contents
Installation and use of Memcache in PHP environment, phpmemcache
Home Backend Development PHP Tutorial Installation and use of Memcache in PHP environment, phpmemcache_PHP tutorial

Installation and use of Memcache in PHP environment, phpmemcache_PHP tutorial

Jul 12, 2016 am 09:05 AM
memcache php use

Installation and use of Memcache in PHP environment, phpmemcache

Memcache is a project of danga.com. It was first served for LiveJournal. Currently, many people around the world use this cache Project to build your own heavy-load website to share the pressure on the database. 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, more detailed information can be found here.

Why are there two names: Memcache and memcached? In fact, 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

It 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 installation refers to PHP (or other programs, Memcache also has other good api interfaces provided) to use the functions provided by Memcache on the server side, which requires PHP to add extensions.

PHP’s Memcache

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

<&#63;php

  //连接

  $mem = new Memcache;

  $mem->connect("db.nowamagic.net", );

  //保存数据

  $mem->set('key', 'This is first value', , );

  $val = $mem->get('key');

  echo "Get key value: " . $val ."<br />";

  //替换数据

  $mem->replace('key', 'This is replace value', , );

  $val = $mem->get('key');

  echo "Get key value: " . $val . "<br />";

  //保存数组

  $arr = array('aaa', 'bbb', 'ccc', 'ddd');

  $mem->set('key', $arr, , );

  $val = $mem->get('key');

  echo "Get key value: ";

  print_r($val);

  echo "<br />";

  //删除数据

  $mem->delete('key');

  $val = $mem->get('key');

  echo "Get key value: " . $val . "<br />";

  //清除所有数据

  $mem->flush();

  $val = $mem->get('key');

  echo "Get key value: ";

  print_r($val);

  echo "<br />";

  //关闭连接

  $mem->close();

&#63;>

Copy after login

If normal, the browser will output:

Get key value: This is first value
Get key value: This is replace value
Get key value: Array ( [] => aaa [] => bbb [] => ccc [] => ddd )
Get key value:
Get key value:

Program code analysis

Initialize a Memcache object: $mem = new Memcache;
Connect to our Memcache server. 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:

1

2

$val = $mem->get('key′);

echo "Get key value: " . $val;

Copy after login

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

1

2

3

$mem->replace('key', 'This is replace value', , );

$val = $mem->get('key');

echo "Get key value: " . $val;

Copy after login

Similarly, Memcache can also save arrays. The following is an array saved in Memcache, then retrieved and output:

1

2

3

4

$arr = array('aaa', 'bbb', 'ccc', 'ddd');

$mem->set('key', $arr, , );

$val = $mem->get('key');

print_r($val);

Copy after login

Now delete a piece of data, use the delte interface, the parameter is a key, and then you can delete the data of the key in the Memcache server. There is no result in the final output:

1

2

3

$mem->delete('key');

$val = $mem->get('key');

echo "Get key value: " . $val . "<br />";

Copy after login

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

1

2

3

4

5

$mem->flush();

$val = $mem->get('key');

echo "Get key value: ";

print_r($val);

echo "<br />";

Copy after login

Using Memcache

Websites that use Memcache generally have relatively large traffic. In order to relieve the pressure on the database, Memcache is used as a cache area to save part of the information in the memory, so that it can be accessed quickly on the front end. Then 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 Applications

Memcache originally supports distributed distribution, 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.

However, this has the disadvantage that it requires judgment on the User ID. If the business is inconsistent, or other types of applications may not be so suitable, then you can consider it based on your actual business, or think of a more suitable method.

Reduce database pressure

This is quite important. All data is basically stored in the database. Frequent access to the database each time leads to a severe decline in database performance and the inability to serve more users at the same time. For example, MySQL is particularly frequent. lock table, then 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 considered:

The back-end database operation module extracts all Select operations (regardless of update/delete/insert), and then performs the corresponding hash algorithm on the corresponding SQL to calculate a hash data key (such as MD5 or SHA), and then Search the data for this key 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 in an array format, and then set the data to Memcache. The key is this SQL hash value, 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.

Memcache security

Our above Memcache server is operated directly through the client connection without any verification process. If the server is directly exposed to the Internet, it is more dangerous. At least the data will be leaked and viewed by other unrelated people. More seriously, the server is invaded because Mecache runs with root privileges, and there may be some unknown bugs or buffer overflows in it. These are unknown to us, so the danger is foreseeable. 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 make the access between the two servers in the form of an intranet, 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 listen to the 11211 port of the 192.168.0.200 IP on the intranet, occupying 1024MB of memory, and allowing a maximum of 1024 concurrent connections.

Set up firewall

Firewall is a simple and effective method. If both servers are connected to the Internet and you need to access Memcache through external IP, you can consider using a firewall or proxy program to filter 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 ... –dport -j ACCEPT
# iptables -A INPUT -p udp -s ... –dport -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 based on your own Need to be done.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1068828.htmlTechArticleInstallation and use of Memcache in PHP environment, phpmemcache Memcache is a project of danga.com, which first served LiveJournal Yes, many people around the world currently use this caching project to build...
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

See all articles