Home Backend Development PHP Tutorial Usage of memcache in PHP database

Usage of memcache in PHP database

May 18, 2018 pm 02:24 PM
memcache php database

This article mainly introduces the usage of memcache in PHP database operation, and analyzes the download, installation, configuration and related usage skills of memcache in detail in the form of examples. Friends in need can refer to it

The details are as follows:

In a highly concurrent web application, database access bottlenecks have always been a big problem. Once a certain limit is reached, the database can easily crash. However, if we put commonly used data into memory, it can be retrieved from it when needed. Fetching from memory not only speeds up reading, but also saves database IO.

memcache introduction

Memcache is a high-performance distributed memory object cache system that maintains a unified huge Hash table, which can be used to store data in various formats, including images, videos, files, and database search results. Simply put, the data is called into the memory and then read from the memory, thus greatly improving the reading speed.

Mem of memcache is memory, cache is cache, and combination means memory cache. When we use memcache, we first read the data from memcache. If it cannot be found, we will search it in the database and store the data in memcache, so that it can be easily found the next time we search.

Note:

memcache is a memory-based database. Due to the closing and releasing characteristics of memory, memcache cannot be persisted. Storage content;
memcache is stored in blocks, so data larger than 1M cannot be stored.
Memcache relies on the libevent library. Before installation, you need to confirm that the libevent library has been installed.
Memcache is a lightweight in-memory database that only supports key-value storage.
There are no settings for users and passwords in memcache, so you must configure the firewall port to restrict connections during configuration to achieve security purposes.
Using repcached can also easily implement memcache's single-master single-slave master-slave replication.

Application scenarios of memcache

Store a large amount of data that does not require persistent storage or that already exists in the database and will not change.
Reading data is very frequent and requires less than 1M.
The data type is simple key-value data.
The calculated results and the rendered web page template file.
Because of its atomic incrementability, it can be used for counting.
Because you can set the data expiration time feature and store the expiration date data. However, it should be noted that memcache will reuse memory based on the least recently used principle (LRU) when the allocated memory is insufficient, which may cause information to be deleted in advance.
Use memcache to store session information to achieve multi-server session sharing. Required configuration: php.ini:

session.save_handler = memcache //设置session的储存方式为memcache 
memcache.hash_strategy = "consistent"//设置memcache的hash算法为一致性哈希算法。 
session.save_path = "tcp:/ip:port" //设置session储存的位置,多台memcache用逗号隔开。
Copy after login

##memcache server installation## The installation of #memcache is simple. The server can be downloaded from its official website http://www.memcached.org/. After decompressing it, run it in its directory./configure -prefix=/path to compile, and then make / make test / make install to get the result. Directly executable binaries.

Use the ./memcached command to start the server. The commonly used parameters are as follows:

-p port listening port (default: 11211)

-d Run Memcached in the background -u username Account running Memcached
-m n Maximum memory usage, unit is MB, default is 64 MB
-c connections Maximum number of connections, default is 1024

Common commands for memcacheAfter connecting to memcache with memcache client or telnet, you can operate memcache.

The memcache data structure is simple, so there are few command line commands. Let’s briefly analyze the command format with a common command:

add key flags expire_time length \r\n value
Copy after login

flags: whether to compress/serialize, usually 0.

expire_time: How long it takes to expire after storage. The unit is seconds (s), and the maximum length is 30 days. The length exceeding 30 days is regarded as a timestamp indicating "when will it expire". If set to 0, it will never expire.

length: value length. After entering the length and pressing Enter, the command line will read the length characters you enter next.

set key flags expire_time length  //如果有值则覆盖原值,没有则新增,add在有值时会存储失败
get key               //获取key的值
replace key flags expire_time length// 替换一个已存在的key
append/preappend key flags expire_time length// 给key的value后面/前面添加新内容。
preappend key flags expire_time length   // 给key的value前面添加新内容。
inc/dec key [n]             //key的值递增/递减1/[n]
delete key               //删除一个key
flush_all [n]              //[在n秒后]删除全部数据
stats [options]             //获取memcache[有关某一项]的详细信息
Copy after login

PHP’s memcache extension and applicationat https://pecl. Search php.net/index.php to obtain the required memcache extension package.

Linux system, directly select the version (the latest stable version is recommended) to download. After decompression, use the phpize tool in the decompression directory to generate the configure file and use it to install. After the installation is completed, add extension in /php.ini. For details, please refer to the previous article: http://www.jb51.net/article/121314.htm.

Under windows, click the "windows logo DLL" link on the right side of the link, and in the newly opened page, select the extension you need according to version, 32-bit/64-bit, thread-safe/non-thread-safe , specific options can be seen on the phpinfo(); page. After the download is complete, put it in the phppath/ext/ directory, then add extension=php_memcacache.dll to php.ini; restart the server to complete the installation.

在phpinfo()页面中看到memcache扩展后,说明安装成功,我们就可以在php脚本中使用关于memcache的类函数库了。

在手册中我们可以找到许多关于php的memcache扩展的使用,以下是一个典型的memcache使用流程。

$m=new Memcache();
$m->connect($host,$port);
$m->add($key,$value[,flags,$expire_time]);
$content=$m->get($key);
$m->close();
Copy after login

这是一个简单的memcache连接程序,在进行memcache分布式存储时,还需要用到$memcache->addServer()向memcache集群中添加服务器。

相关推荐:

ThinkPHP框架中使用Memcached缓存数据步骤详解

ThinkPHP框架中使用Memcached缓存数据的方法

php-memcached扩展安装

The above is the detailed content of Usage of memcache in PHP database. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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

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

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,

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

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

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

See all articles