Usage of memcache in 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用逗号隔开。
##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
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[有关某一项]的详细信息
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();
这是一个简单的memcache连接程序,在进行memcache分布式存储时,还需要用到$memcache->addServer()
向memcache集群中添加服务器。
相关推荐:
ThinkPHP框架中使用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!

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

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

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

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 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 uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.
