一、MemCache简介
MemCache是一个高性能的分布式的内存对象缓存系统,用于各种动态应用以减轻数据库负担。它通过在内存中缓存数据和对象,来减少读取数据库的次数, 从而提高动态、数据库驱动应用速度。MemCache会在内存中开辟一块空间,建立一个统一的巨大的hash表,hash表能够用来存储各种格式的数据, 包括图像、视频、文件以及数据库检索的结果等。
二、环境配置
搭建好lnmp架构:
php安装与配置
nginx安装与配置
mysql安装与配置
三、实现访问加速
1.下载编译memcache
[root@server1 lnmp]# tar zxf memcache-2.2.5.tgz ##解压
[root@server1 lnmp]# cd memcache-2.2.5
[root@server1 memcache-2.2.5]# vim ~/.bash_profile #增加php的环境变量
13 PATH=$PATH:$HOME/bin:/usr/local/lnmp/mysql/bin:/usr/local/lnmp/php/bin
[root@server1 memcache-2.2.5]# source ~/.bash_profile #重新加载系统环境变量
[root@server1 memcache-2.2.5]# ls ##进入解压后的目录后,没有configure的选项
[root@server1 memcache-2.2.5]# phpize #通过phpize命令生成configure
Configuring for:
PHP Api Version: 20131106
Zend Module Api No: 20131226
Zend Extension Api No: 220131226
[root@server1 memcache-2.2.5]# ls
编译安装:
./configure ##编译
make && make install
2.配置缓存
[root@server1 memcache-2.2.5]# cd /usr/local/lnmp/php/etc/
[root@server1 etc]# ls
pear.conf php-fpm.conf php-fpm.conf.default php.ini
[root@server1 etc]# vim php.ini
873 extension=memcache.so ##将memcache模块添加到php中
[root@server1 etc]# /etc/init.d/php-fpm reload ##重新加载php服务
Reload service php-fpm done
[root@server1 etc]# php -m | grep memcache ##查看php下加载的模块是否有memcache
memcache
yum install -y memcached ##安装memcached
vim /etc/sysconfig/memcached ##查看memcached的启动配置,监控端口为所有主机的11211端口
/etc/init.d/memcached start ##启动memcached服务
3.测试端口:
yum install telnet -y
[root@server1 etc]# telnet localhost 11211 #远程登陆本地的11211端口,用于测试缓存功能
Trying ::1...
Connected to localhost.
Escape character is '^]'.
set name 0 0 6 #最大字节数为6
westos
STORED
aaaaaaa
ERROR
get name
VALUE name 0 6
westos
END
stats ##可查看版本信息
STAT pid 3890
STAT uptime 221
STAT time 1556629860
STAT version 1.4.4
STAT pointer_size 64
STAT rusage_user 0.000000
STAT rusage_system 0.005999
STAT curr_connections 10
STAT total_connections 11
......
4.修改默认发布测试页
[root@server1 etc]# cd /mnt/lnmp/memcache-2.2.5
[root@server1 memcache-2.2.5]# ls
[root@server1 memcache-2.2.5]# cp memcache.php example.php /usr/local/lnmp/nginx/html/
[root@server1 memcache-2.2.5]# cd /usr/local/lnmp/nginx/html
[root@server1 html]# vim memcache.php ##修改统计访问的页面文件
define('ADMIN_PASSWORD','westos'); ##将登陆密码修改为westos
$MEMCACHE_SERVERS[] = '172.25.60.1:11211'; ##添加测试的后台服务器的ip
#$MEMCACHE_SERVERS[] = 'mymemcache-server2:11211'; ##因为只配置了一台服务器,所以多出的注释
5.测试:
打开firefox:http://172.25.60.1/memcache.php
命中率为50%
可以统计访问172.25.60.1/example.php页面的具体结果,是去访问的缓存还是后台的服务器
第一次访问:172.25.60.1/example.php
第十次访问:172.25.60.1/example.php
6.在真机上:
模拟5台主机并发访问2000次主页的情况
ab -c 5 -n 2000 http://172.25.60.1/index.php
175次失败,时间14.417秒
ab -c 5 -n 1000 http://172.25.60.1/example.php
0次失败,时间1.110秒
可以看到访问缓存的时间效率远远大于直接访问后台服务器