


Memcache class that supports group operations in PHP_PHP Tutorial
Memcache is a cache method commonly used in PHP development and is an essential component in high-concurrency systems.
In actual development, Memcache has an unsatisfactory problem, that is, Memcache cannot support group operations on keys.
Group operations can also be called domain operations. For example, an article system uses Memcache in the front-end part to cache list page data and article detail page data. Both types of data are relatively large. Then, when an article is published in the background, the list page should be updated to the latest list - which may involve many list pages. Of course, for the article detail page, it does not need to be updated.
Okay, at this time we need to delete the original cache so that the program can automatically update the list page data. However, there is a problem with using Memcache's flush function, that is, it will clear all data, including the data of list pages and article pages. Under large concurrency conditions, when all caches are deleted and the cache is rebuilt, there will be a very high load. produce.
In addition, there may be situations where some cache variables that you do not want to delete will be lost, such as program configurations, database table structures that are cached to speed up, etc.
So we need a caching mechanism that supports group operations. We can set the list page to one group, the article page data to another group, the program configuration to another group, and so on. When you need to rebuild the list page, you only need to delete all the data in the list page group without affecting the data in other groups.
After testing several solutions, the following solution is still the most ideal and fast. Let’s look at the code first, and then talk about the principle:
class MyCache
{
Private $mmc = null;
Private $group = null;
private $version = 1;
Function __construct($group){
If(!class_exists('mmcache')){
$this->mmc = false;
return;
}
$this->mmc = new memcache();
$this->mmc->addServer('192.168.1.5', 11211);
$this->mmc->addServer('192.168.1.6', 11211);
$this->group = $group;
$this->version = $this->mmc->get('version_'.$group);
}
Function set($key, $var, $expire=3600){
If(!$this->mmc)return;
Return $this->mmc->set($this->group.'_'.$this->version.'_'.$key, $var, $expire);
}
Function get($key){
If(!$this->mmc)return;
Return $this->mmc->get($this->group.'_'.$this->version.'_'.$key);
}
Function incr($key, $value=1){
If(!$this->mmc)return;
Return $this->mmc->increment($this->group.'_'.$this->version.'_'.$key, $value);
}
Function decr($key, $value=1){
If(!$this->mmc)return;
Return $this->mmc->decrement($this->group.'_'.$this->version.'_'.$key, $value);
}
Function delete($key){
If(!$this->mmc)return;
Return $this->mmc->delete($this->group.'_'.$this->version.'_'.$key);
}
Function flush(){
If(!$this->mmc)return;
++$this->version;
$this->mmc->set('version_'.$this->group, $this->version);
}
}
?>
The above class is relatively complete, including linking to the Memcache service, setting and getting values, increasing and decreasing values, as well as deleting keys and deleting all (flush). This includes regular Memcache operation functions and extensions to full delete (flush) operations.
As you can see from the code, the flush function of the support group is implemented through the version key. That is, every time the variable of the group is saved, the key of the variable will add the version value, and the version value is a number (from 1), the version value will be used when storing and retrieving keys.
When a developer wants to flush the data of the current group, the flush operation simply changes some version values (plus one). Then, the next time the key is accessed, the original value will not be obtained - because the version has changed. , that is, the key name has been changed. In this way, the original value will be automatically recycled by Memcache without any efficiency overhead. Moreover, the program only adds the storage and retrieval of a version, the amount of data is extremely small, and it basically has no impact on the system efficiency.
Through the above classes, group operations can be performed on the Memcache cache. This PHP class can also be extended, such as adding a socket to directly access the interface function of memcache. In this way, there is no need to install the memcache extension class in the PHP environment, which is more effective. This avoids misoperation of flush, and after adding caching mechanisms such as apc, socket access to the memcache interface will not be much slower than expansion.
In addition, the MyCache class has an additional function: when the memcache service fails, the MyCache class simply returns a null value without directly making an error.
The following is the usage method of MyCache class:
//Introduce definition
include('MyCache.php');
// Instantiate
$mc = new MyCache('abc'); // Requires domain
// Set value
$mc->set('word', 'hello world', 900);
// Get value
echo $mc->get('word');
// Delete value
$mc->delete('word');
echo $mc->get('word');
$mc->set('counter', 1, 290000);
echo $mc->get('counter');
// Add value
$mc->incr('counter');
$mc->incr('counter');
echo $mc->get('counter');Memcache is a cache method commonly used in PHP development and is an essential component in high-concurrency systems.
In actual development, Memcache has an unsatisfactory problem, that is, Memcache cannot support group operations on keys.
Group operations can also be called domain operations. For example, an article system uses Memcache in the front-end part to cache list page data and article detail page data. Both types of data are relatively large. Then, when an article is published in the background, the list page should be updated to the latest list - which may involve many list pages. Of course, for the article detail page, it does not need to be updated.
Okay, at this time we need to delete the original cache so that the program can automatically update the list page data. However, there is a problem with using Memcache's flush function, that is, it will clear all data, including the data of list pages and article pages. Under large concurrency conditions, when all caches are deleted and the cache is rebuilt, there will be a very high load. produce.
In addition, there may be situations where some cache variables that you do not want to delete will be lost, such as program configurations, database table structures that are cached to speed up, etc.
So we need a caching mechanism that supports group operations. We can set the list page to one group, the article page data to another group, the program configuration to another group, and so on. When you need to rebuild the list page, you only need to delete all the data in the list page group without affecting the data in other groups.
After testing several solutions, the following solution is still the most ideal and fast. Let’s look at the code first, and then talk about the principle:
class MyCache
{
Private $mmc = null;
private $group = null;
private $version = 1;
Function __construct($group){
If(!class_exists('mmcache')){
$this->mmc = false;
return;
}
$this->mmc = new memcache();
$this->mmc->addServer('192.168.1.5', 11211);
$this->mmc->addServer('192.168.1.6', 11211);
$this->group = $group;
$this->version = $this->mmc->get('version_'.$group);
}
function set($key, $var, $expire=3600){
if(!$this->mmc)return;
return $this->mmc->set($this->group.'_'.$this->version.'_'.$key, $var, $expire);
}
function get($key){
if(!$this->mmc)return;
return $this->mmc->get($this->group.'_'.$this->version.'_'.$key);
}
function incr($key, $value=1){
if(!$this->mmc)return;
return $this->mmc->increment($this->group.'_'.$this->version.'_'.$key, $value);
}
function decr($key, $value=1){
if(!$this->mmc)return;
return $this->mmc->decrement($this->group.'_'.$this->version.'_'.$key, $value);
}
function delete($key){
if(!$this->mmc)return;
return $this->mmc->delete($this->group.'_'.$this->version.'_'.$key);
}
function flush(){
if(!$this->mmc)return;
++$this->version;
$this->mmc->set('version_'.$this->group, $this->version);
}
}
?>
上面的类比较完整,包括链接Memcache服务,设置和获取值,增减值,还有删除key和全删除(flush)。这里包括了常规的Memcache操作功能,和对全删除(flush)操作的扩展。
从代码可以看到,支持组的flush功能的实现,是通过version这个key来实现的,也就是每次存该组的变量的时候,变量的key都会加入version值,version值是一个数字(从1开始),当存和取key的时候,version值都会被使用到。
当开发者要flush当前组的数据的时候,flush操作只是简单地改变一些version的值(加一),那么,下次存取key的时候,将获取不到原来的值——因为version改变了,也就是取的key名称已经改变了。这样原有的值会被Memcache自动回收,不会出现任何的效率开销。而且程序上只是增加一个version的存和取,数据量极小,对系统效率基本没有任何影响。
通过以上的类,可以针对Memcache缓存进行组的操作,而这个PHP类,还可以继续扩展,如加入socket直接访问memcache的接口功能,这样PHP环境中就不需要安装memcache扩展类了,这样更有效避免flush的误操作了,而且在加入apc等缓存机制后,socket访问memcache接口也不会比扩展慢多少。
另外,MyCache类还有个附加的功能:当memcache服务失效的时候,MyCache类只是简单返回空值,而不会直接出错。
以下附带MyCache类的使用方法:
// 引入定义
include('MyCache.php');
// 实例化
$mc = new MyCache('abc'); // 要有域
// 设置值
$mc->set('word', 'hello world', 900);
// 取得值
echo $mc->get('word');
// 删除值
$mc->delete('word');
echo $mc->get('word');
$mc->set('counter', 1, 290000);
echo $mc->get('counter');
// 增加值
$mc->incr('counter');
$mc->incr('counter');
echo $mc->get('counter');
// 减少值
$mc->decr('counter');
echo $mc->get('counter');
// 按组删
$mc->flush();
本文出自 “振中的技术记事本” 博客
// 减少值
$mc->decr('counter');
echo $mc->get('counter');
// Delete by group
$mc->flush();
Author "Zhenzhong's Technical Notepad"

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.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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

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