PHP Memcache and Memcached

不言
Release: 2023-03-23 06:00:01
Original
10470 people have browsed it

This article introduces Memcache and Memcached in PHP. Friends who are interested can take a look

**Memcache introduction:**Memcache is a distributed cache system. Distributed is It is said that the Memcache service can be installed on multiple servers at the same time, so that a good cluster effect can be achieved. High speed is because Memcache data is maintained in memory, and its reading speed is much faster than the reading speed of data stored in the hard disk.
Function:When our application traffic is relatively large, the pressure on the database will be particularly high. Memcache can add a buffer layer between the application and the database, which is what we have already obtained from the database before. When we read the data for the second time or next time, we can directly access Memcache to read the data, thereby reducing the pressure on databases such as Mysql.
How to manage Memcache:In fact, it can be understood that it is a database with only one table. This table has two fields, namely key and value. Value is the saved data, and key is the ID of the data, which is used to ensure the search results. Uniqueness
Usage scenarios:
(1) Non-persistent storage: The requirements for data storage are not high, that is to say, if this data is lost, it will not cause much damage to the system. The impact is because when the system is powered off or restarted, the memory will be cleared, and the data previously stored in Memcache will also be cleared. Therefore, Memcache should be used as a cache, not as a real database
(2) Distributed storage: not suitable for stand-alone use, because Memcache consumes a lot of memory. If you use Memcache, it is recommended to install it on another computer. Use a single machine as a cache system instead of installing both Memcache and database on one machine.
(3) Key/Value storage: simple format, does not support List, Array data formats

Memcached and Memcache are two versions, Memcached is recommended, it has more improvements and functions, it is Memcache The upgraded version has higher speed and stability

Installing Memcached
1, Memcache server installation
(1) Compile and install, Libevent Memcache
First install the Libevent extension. The advantage of compiling and installing is that you can make some customized settings during the installation process, such as specifying where the software is installed, such as what errors occurred during the compilation and installation process, and I don’t know much about Linux. In this case, it may be relatively difficult for you to handle errors
(2) Use the dependency management tools yum and apt-get to install

Actual installation: (The operating system is 64-bit Centos)
If you want to compile and install, you need to download the installation package libevent and memcached in advance
Use the dependency management tool to install here

#yum install memcached
Copy after login
Copy after login

Start memcached

#/usr/bin/memcached -d -l 127.0.0.1 -p 11211 -m 150 -u root/*
    -d:守护进程的模式启动。守护进程就是,当你从终端窗口推出之后,程序依然进行    -l:指定IP地址    -p:指定端口号    -m:为memcached分配多少内存,这里是以M为单位    -u:以哪个身份去启动memcached(线上的时候最好不要用超级管理员用户)*/
Copy after login
Copy after login

You can use ps to check whether the memcached process is started.

#ps -ef | grep memcached
Copy after login
Copy after login

2, Memcache client installation
1, install the front-end extension Libmemcached
Download libmemcached and memcached, decompress libmemcached
Use compile and install here, Enter the decompressed folder
Execute

#./configure --prefix=/usr/lib/libmemcached然后执行#make && makeinstall
Copy after login
Copy after login

2, install memcached extension for php
Extract memcached and enter the decompression directory
Use phpize to install the memcached extension

#phpize此时就会做出一个configure的文件#./configure --with-php-config=/usr/local/php/bin/php-config --with-libmemcached-dir=/usr/lib/libmemcached-sasl后边是指定php的配置文件和刚安装的libmemcached的位置,大家根据自己的配置文件路径进行填写#make#make install执行完make install之后,我们会看见一个扩展目录,将该路径添加到php配置文件中
php.ini中加入
extension=memcached.so
然后重启服务器环境,查看php扩展#php -m | grep memecached
Copy after login
Copy after login

Use memcached in PHP
System classes: addServer, addServers, getStats, getVersion
Data classes: add, set, delete, flush, replace, increment, get
Advanced classes: setMulti, deleteMulti, getMulti, getResultCode, getResultMessage
For more operations on memecached, you can check it out on the php official website (php.net)

test.php<?php/*系统类*/$m = new Memcached();/*添加服务器*/$m->addServer(&#39;127.0.0.1&#39;, 11211);/*添加多台服务器*/$array = array(    array(&#39;127.0.0.1&#39;, 11211),    array(&#39;127.0.0.1&#39;, 11211)
);$m->addServers($array);/*查看服务器状态*/print_r($m->getStats());/*查看服务端版本号*/print_r($m->getVersion());/*数据类*/$m->add(&#39;mkey&#39;, &#39;mvalue&#39;, 0);//第三个参数是数据存在的时间,0表示永久echo $m->get(&#39;mkey&#39;);//获取数据/*假设对同一个key值进行两次添加的话,后边的操作不会覆盖前边的value,如果想替换掉,就使用replace*/$m->replace(&#39;mkey&#39;, &#39;mvalue2&#39;);/*还可以使用set方法表添加数据,它的好处就是,当我们的数据不存在时会帮我们新建数据,如果存在,就会覆盖原值*/$m->add(&#39;mkey&#39;, &#39;mvalue&#39;, 600);/*删除数据*/$m->delete(&#39;mkey&#39;);/*清空memcache中的所有缓存*/$m->flush();/*对memcache中整形数据进行+1或+任意数值的操作*/$m->set(&#39;num&#39;, 5, 0);$m->increment(&#39;num&#39;, 5);//每次刷新页面,num自增5$m->get(&#39;num&#39;);/*自减decrement用法相同*//*下边的方法只支持Memcached,不支持Memcache*//*一次添加多条数据*///原始方法,多次使用set()//现在可以使用setMulti()$data = array(    &#39;key&#39; => &#39;value&#39;,    &#39;key1&#39;=> &#39;value1&#39;);$m->setMulti($data,0);$result = $m->getMulti(array(&#39;key&#39;,&#39;key1&#39;));//获取多条数据print_r($result);//删除多条数据$m->deleteMulti(array(&#39;key&#39;,&#39;key1&#39;));//返回上一次操作返回的编码(数字的形式存在) 可以到手册中查看每一个编码的含义 echo $m->getResultCode();//比如  成功  返回0//获取操作结果echo $m->getResultMessage();//比如  成功  返回SUCCESS
Copy after login
Copy after login

Encapsulate an own Memcache class

Memcached.class.php<?php/*
封装自己的Memcached类
1,扩展性
2,可调性
3,尽量简便的操作,一个方法多种功能
*//*
通过一个s()方法实现set()、get()、delete()操作
set    s($key,$value,$time)
get    s($key)
delete s($key,NULL)
*/class Mem
{    private $type = &#39;Memcached&#39;;//考虑到扩展性,实例化的可能是Memcache也可能是Memcached
    private $m;    private $time = 0;    private $error;    private $debug = &#39;true&#39;;    public function __construct()
    {         if(!class_exists($this->type)){            $this->error="No ".$this->type;            return false;
        }else{            $this->m=new $this->type;
        }
    }    //添加服务器
    public function addServer($arr)
    {        $this->m->addServers($arr);
    }    public function s($key, $value=&#39;&#39;, $time=NULL)
    {        $number = func_num_args();//该函数用来判断传递过来了几个参数
        if($number == 1){            return $this->get($key);
        }else if($number >= 2){            if($value === NULL){//一定要使用“全等于”,因为如果不是全等于,传递过来0也会通过
                $this->delete($key);
            }else{                $this->set($key, $value, $time);
            }
        }
    }    private function set($key, $value, $time=NULL)
    {        if($time === NULL)            $time = $this->time();        $this->m->set($key, $value, $time);        if($this->debug){            if($this->m->getResultCode() != 0){                return false;
            }
        }
    }    private function get($key){        $result = $this->m->get($key);        if($this->debug){            if($this->m->getResultCode() != 0){                return false;
            }
        }        return $result;
    }    private function delete($key)
    {        $this->m->delete($key);
    }    public function getError()
    {        if($this->error){            return $this->error();
        }else{            return $this->m->getResultMessage();
        }
    }

}
Copy after login

Use Memcache in the project
1, generate cache instantly
It is more suitable for news details pages. When the first person enters the page, a cache is generated. When subsequent people enter the page again, the data can be obtained directly from the cache and an expiration time can be set for the data. This way If so, you can clear the cache in time when there are fewer people watching the news, which can achieve the purpose of saving memory
2, generate the cache in advance
This method of generating cache is relatively It is suitable for situations where the number of visits is relatively large and the amount of data is large, similar to the homepage of the website. You can use a scheduled script to generate cache
3 in advance, and permanent cache
This caching solution is more suitable for individual pages, and its modification frequency is very low. At this time, it can be generated Permanent cache

**Memcache介绍:**Memcache是一套分布式缓存系统,分布式就是说可以在多台服务器上同时安装Memcache服务,这样可以达到很好的集群效果。高速,是因为Memcache数据都是维护在内存中的,它的读取速度比存储在硬盘中的数据的读取速度要快很多。
作用:当我们的应用访问量比较大的时候,数据库的压力也会特别大,Memcache可以在应用和数据库之间增加一个缓冲层,就是我们之前从数据库中已经读取到的数据,我们第二次或者是接下来再读取的时候,就可以直接访问Memcache去读取这些数据,从而减轻Mysql等等数据库的压力
怎样理Memcache:其实可以理解成,它是一个只有一张表的数据库,这张表有两个字段,分别是key和value,value是保存的数据,key就是这个数据的ID,用来保证查找时的唯一性
使用场景:
(1)非持久化存储:对数据存储要求不高,也就是说,如果这份数据丢失,也不会对系统造成太大的影响,因为当系统断电或被重启后内存会被清空掉,那么之前保存在Memcache中的数据也会被清空掉。所以要把Memcache当作缓存使用,而不要当成真正的数据库
(2)分布式存储:不适合单机使用,因为Memcache对内存的消耗很大,如果使用Memcache,推荐将其安装在另外一台机器上单独作为缓存系统,而不要把Memcache和数据库都装到一台机器。
(3)Key/Value存储:格式简单,不支持List、Array数据格式

Memcached和Memcache是两个版本,推荐Memcached,它有更多的改进和功能函数,是Memcache的升级版本,速度和稳定性都比较高

安装Memcached
1,Memcache服务端的安装
(1)编译安装,Libevent Memcache
先安装Libevent这个扩展,编译安装的好处就是可以在安装的过程进行一些自定义的设置,比如指定软件安装在哪儿,比如编译安装过程出现了哪些错误,而对Linux了解不是特别多的情况下,你可能处理错误的时候就会相对困难
(2)使用依赖管理工具yum、apt-get进行安装

实际安装:(操作系统是64位的Centos)
如果要编译安装,需要将安装包提前下载下来libevent、memcached
这里使用依赖管理工具安装

#yum install memcached
Copy after login
Copy after login

启动memcached

#/usr/bin/memcached -d -l 127.0.0.1 -p 11211 -m 150 -u root/*
    -d:守护进程的模式启动。守护进程就是,当你从终端窗口推出之后,程序依然进行    -l:指定IP地址    -p:指定端口号    -m:为memcached分配多少内存,这里是以M为单位    -u:以哪个身份去启动memcached(线上的时候最好不要用超级管理员用户)*/
Copy after login
Copy after login

可以使用ps查看memcached进程是否启动

#ps -ef | grep memcached
Copy after login
Copy after login

2,Memcache客户端的安装
1,安装前置扩展Libmemcached
下载好libmemcached和memcached,对libmemcached进行解压
这里使用编译安装,进入解压出来的文件夹
执行

#./configure --prefix=/usr/lib/libmemcached然后执行#make && makeinstall
Copy after login
Copy after login

2,为php安装memcached扩展
解压memcached,进入到解压目录当中
使用phpize的方式安装memcached扩展

#phpize此时就会做出一个configure的文件#./configure --with-php-config=/usr/local/php/bin/php-config --with-libmemcached-dir=/usr/lib/libmemcached-sasl后边是指定php的配置文件和刚安装的libmemcached的位置,大家根据自己的配置文件路径进行填写#make#make install执行完make install之后,我们会看见一个扩展目录,将该路径添加到php配置文件中
php.ini中加入
extension=memcached.so
然后重启服务器环境,查看php扩展#php -m | grep memecached
Copy after login
Copy after login

在PHP中使用memcached
系统类:addServer、addServers、getStats、getVersion
数据类:add、setdelete、flush、replace、increment、get
进阶类:setMulti、deleteMulti、getMulti、getResultCode、getResultMessage
更多关于memecached的操作,可以到php官网查看(php.net)

test.php<?php/*系统类*/$m = new Memcached();/*添加服务器*/$m->addServer(&#39;127.0.0.1&#39;, 11211);/*添加多台服务器*/$array = array(    array(&#39;127.0.0.1&#39;, 11211),    array(&#39;127.0.0.1&#39;, 11211)
);$m->addServers($array);/*查看服务器状态*/print_r($m->getStats());/*查看服务端版本号*/print_r($m->getVersion());/*数据类*/$m->add(&#39;mkey&#39;, &#39;mvalue&#39;, 0);//第三个参数是数据存在的时间,0表示永久echo $m->get(&#39;mkey&#39;);//获取数据/*假设对同一个key值进行两次添加的话,后边的操作不会覆盖前边的value,如果想替换掉,就使用replace*/$m->replace(&#39;mkey&#39;, &#39;mvalue2&#39;);/*还可以使用set方法表添加数据,它的好处就是,当我们的数据不存在时会帮我们新建数据,如果存在,就会覆盖原值*/$m->add(&#39;mkey&#39;, &#39;mvalue&#39;, 600);/*删除数据*/$m->delete(&#39;mkey&#39;);/*清空memcache中的所有缓存*/$m->flush();/*对memcache中整形数据进行+1或+任意数值的操作*/$m->set(&#39;num&#39;, 5, 0);$m->increment(&#39;num&#39;, 5);//每次刷新页面,num自增5$m->get(&#39;num&#39;);/*自减decrement用法相同*//*下边的方法只支持Memcached,不支持Memcache*//*一次添加多条数据*///原始方法,多次使用set()//现在可以使用setMulti()$data = array(    &#39;key&#39; => &#39;value&#39;,    &#39;key1&#39;=> &#39;value1&#39;);$m->setMulti($data,0);$result = $m->getMulti(array(&#39;key&#39;,&#39;key1&#39;));//获取多条数据print_r($result);//删除多条数据$m->deleteMulti(array(&#39;key&#39;,&#39;key1&#39;));//返回上一次操作返回的编码(数字的形式存在) 可以到手册中查看每一个编码的含义 echo $m->getResultCode();//比如  成功  返回0//获取操作结果echo $m->getResultMessage();//比如  成功  返回SUCCESS
Copy after login
Copy after login

封装一个自己的Memcache类

Memcached.class.php<?php/*
封装自己的Memcached类
1,扩展性
2,可调性
3,尽量简便的操作,一个方法多种功能
*//*
通过一个s()方法实现set()、get()、delete()操作
set    s($key,$value,$time)
get    s($key)
delete s($key,NULL)
*/class Mem
{    private $type = &#39;Memcached&#39;;//考虑到扩展性,实例化的可能是Memcache也可能是Memcached
    private $m;    private $time = 0;    private $error;    private $debug = &#39;true&#39;;    public function __construct()
    {         if(!class_exists($this->type)){            $this->error="No ".$this->type;            return false;
        }else{            $this->m=new $this->type;
        }
    }    //添加服务器
    public function addServer($arr)
    {        $this->m->addServers($arr);
    }    public function s($key, $value=&#39;&#39;, $time=NULL)
    {        $number = func_num_args();//该函数用来判断传递过来了几个参数
        if($number == 1){            return $this->get($key);
        }else if($number >= 2){            if($value === NULL){//一定要使用“全等于”,因为如果不是全等于,传递过来0也会通过
                $this->delete($key);
            }else{                $this->set($key, $value, $time);
            }
        }
    }    private function set($key, $value, $time=NULL)
    {        if($time === NULL)            $time = $this->time();        $this->m->set($key, $value, $time);        if($this->debug){            if($this->m->getResultCode() != 0){                return false;
            }
        }
    }    private function get($key){        $result = $this->m->get($key);        if($this->debug){            if($this->m->getResultCode() != 0){                return false;
            }
        }        return $result;
    }    private function delete($key)
    {        $this->m->delete($key);
    }    public function getError()
    {        if($this->error){            return $this->error();
        }else{            return $this->m->getResultMessage();
        }
    }

}
Copy after login

项目中使用Memcache
1,即时生成缓存
比较适用于类似于新闻详情页,第一个人进入页面时,生成缓存,当后边的人再进入这个页面时,可以直接从缓存中获取数据,并且可以给数据设置一个过期时间,这样的话,等看这个新闻的人比较少的时候就可以及时清除缓存,这样可以达到节约内存的目的
2,提前生成缓存
这种生成缓存的方式,比较适用于访问量比较大且数据量比较多,类似于网站首页这种情况。可以使用定时脚本的方式,提前将缓存生成
3,永久缓存
这种缓存方案比较适合于关于单独的页面,它的修改频率非常低,这时可以生成永久缓存

相关推荐:

php模块memcache和memcached区别分析_PHP教程

The above is the detailed content of PHP Memcache and Memcached. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template