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!

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

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

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

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.


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

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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