search
HomeBackend DevelopmentPHP TutorialPHP之分布式缓存memcached熟习和操作

PHP之分布式缓存memcached熟悉和操作

如今互联网崛起的时代,各大网站都面临着一个大数据流问题,怎么提高网站访问速度,减少对数据库的操作;作为PHP开发人员,我们一般能想到的方法有页面静态化处理、防盗链、CDN内容分发加速访问、mysql数据库优化建立索引、架设apache服务器集群()、还有就是现在流行的各种分布式缓存技术:如memcached/redis;


1.什么是Memcached?

a.Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载。它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态、数据库驱动网站的速度。Memcached基于一个存储键/值对的hashmap。其守护进程(daemon )是用C写的,但是客户端可以用任何语言来编写,并通过memcached协议与守护进程通信。

b.Memcached的键key一般是字符串,该值不能重复;value可以放入字符串、数组、数值、对象、布尔,二进制数据和图片视频

c.Memcached默认服务端口是11211

2.PHP使用Memcached步骤

准备:下载Memcached服务安装包:memcached-1.2.6-win32-bin.7z和访问Memcached服务的dll库:php_memcache.dll

www.memcached.org(官网进不去好像,可以从其他地方下载)

解压包memcached-1.2.6-win32-bin.7z(可以解压完复制放到web服务器同级目录),然后操作cmd,进入到刚才解压的目录用命令安装:memcached.exe -d install

安装完(判断是否安装完毕可以到服务列表里面查看是否有memcached服务),然后cmd用命令启动:memcached.exe -d start

具体操作如下:



启动完memcached服务后,再把下载的php_memcache.dll放到web服务器php5目录下的ext目录下


在php.ini里面修改,加载扩展库php_memcache.dll,然后重启apache服务器


开始实践,memcached主要有crud操作(即创建、读取、更新、删除值操作,具体可以查阅手册),下面弄个简单的设置值,然后读取值的操作

a.设置值页面

<?phpheader ("Content-type:text/html;charset=utf-8");//创建Memcache对象$mem = new Memcache();  //连接Memcache服务器if(!$mem->connect("127.0.0.1")) {    echo "连接Memcache服务器失败!";}//设置,'myword'参数代表键key,'hello world'代表存放的值,MEMCACHE_COMPRESSED代表压缩内容,50代表存放时间,单位秒if ($mem->set('myword','hello world',MEMCACHE_COMPRESSED,50)){    echo "设置值成功!";}?>


注:如果值在内存存放的时间要超过30天,要用时间戳来设置100天:如time()+3600*24*100;设置0则表示永不过期


b.读取值页面

<?phpheader ("Content-type:text/html;charset=utf-8");$mem = new Memcache();  if(!$mem->connect("127.0.0.1")) {    echo "连接Memcache服务器失败!";}//读取键myword值$value = $mem->get('myword');if(!$value){    echo "读取失败!";}else{    echo "读取的值=".$value;}

c.删除、更新例子:

<?phpheader ("Content-type:text/html;charset=utf-8");//创建Memcache对象$mem = new Memcache();  //连接Memcache服务器if(!$mem->connect("127.0.0.1")) {    echo "连接Memcache服务器失败!";}//设置,'myword'参数代表键key,'hello world'代表存放的值,MEMCACHE_COMPRESSED代表压缩内容,50代表存放时间,单位秒if ($mem->set('myword','hello world',MEMCACHE_COMPRESSED,50)){    echo "设置值成功!";}//读取键myword值$value = $mem->get('myword');if(!$value){    echo "读取失败!";}else{    echo "读取的值=".$value;}//更新键值$mem->replace('myword','hello everybody!');$value = $mem->get('myword');if(!$value){    echo "读取失败!";}else{    echo "读取的值=".$value;}//删除键myword值$mem->delete('myword');$value = $mem->get('myword');if(!$value){    echo "读取失败!";}else{    echo "读取的值=".$value;}//关闭$mem->close();  ?>

注:mem对象下还有许多方法,可以通过翻阅手册了解。

多个memcached服务器设置,其实就比一个memcached服务器改变一点点,就是把多个memcached的服务器通过方法addserver添加到连接池中,这样设置完后,crud操作时,内部就会通过相应算法均衡连接相应服务器并执行相应操作中。

<?phpheader ("Content-type:text/html;charset=utf-8");//创建Memcache对象$mem = new Memcache(); //添加多台memcached服务器$mem->addserver('192.168.0.1',11211); $mem->addserver('192.168.0.2',11211);$mem->addserver('192.168.0.3',11211);$mem->addserver('192.168.0.4',11211);//设置,'myword'参数代表键key,'hello world'代表存放的值,MEMCACHE_COMPRESSED代表压缩内容,50代表存放时间,单位秒if ($mem->set('myword','hello world',MEMCACHE_COMPRESSED,50)){    echo "设置值成功!";}//读取键myword值$value = $mem->get('myword');if(!$value){    echo "读取失败!";}else{    echo "读取的值=".$value;}?>

memcache的访问是无用户状态,安全性需要考虑,一般通过放在内网,并通过防火墙限制外网访问memcache端口来达到安全

通过修改php.ini,可以把session的值放入memcache服务器中

session.save_handler = files改成session.save_handler = memcached

 session.save_path = "N;MODE;/path"改成 session.save_path = "tcp://127.0.0.1:11211"






Statement
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
What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

What are some performance considerations when using PHP sessions?What are some performance considerations when using PHP sessions?May 02, 2025 am 12:11 AM

PHP sessions have a significant impact on application performance. Optimization methods include: 1. Use a database to store session data to improve response speed; 2. Reduce the use of session data and only store necessary information; 3. Use a non-blocking session processor to improve concurrency capabilities; 4. Adjust the session expiration time to balance user experience and server burden; 5. Use persistent sessions to reduce the number of data read and write times.

How do PHP sessions differ from cookies?How do PHP sessions differ from cookies?May 02, 2025 am 12:03 AM

PHPsessionsareserver-side,whilecookiesareclient-side.1)Sessionsstoredataontheserver,aremoresecure,andhandlelargerdata.2)Cookiesstoredataontheclient,arelesssecure,andlimitedinsize.Usesessionsforsensitivedataandcookiesfornon-sensitive,client-sidedata.

How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

See all articles

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use