search
HomeBackend DevelopmentPHP TutorialPHP之分布式缓存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
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality.Customizing/Extending Frameworks: How to add custom functionality.Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

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.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool