memcache缓存服务器的安装和配置
部署环境:
主机 | ip地址 | 操作系统 |
---|---|---|
nginx | 172.16.1.100 | CentOS 7.3 |
php+memcache | 172.16.1.110 | CentOS 7.3 |
Mysql | 172.16.1.120 | CentOS 7.3 |
memcached | 172.16.1.130 | CentOS 7.3 |
一, 环境准备:
搭建LNMP环境(动态解析)
1,安装nginx
1)安装依赖工具包:[root@nginx-server ~]# yum -y install gcc* pcre-devel openssl-devel zlib-devel make vim
2)创建nginx用户组和用户:[root@nginx-server ~]# groupadd -r nginx && useradd -r -g nginx -s /bin/false -M nginx
3)解压源码包,配置&&编译安装:[root@nginx-server ~]# tar zxf nginx-1.8.0.tar.gz [root@nginx-server ~]# cd nginx-1.8.0[root@nginx-server nginx-1.8.0]# ./configure --help ##可以查看自己需要的模块 --with,或取消的模块-without#根据自己的需求添加不同的模块[root@nginx-server nginx-1.8.0]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx \> --with-http_stub_status_module --with-http_ssl_module --with-http_dav_module --with-http_flv_module \> --with-http_mp4_module --with-http_gzip_static_module --with-http_gzip_static_module \> --with-http_addition_module --with-http_sub_module --with-pcre[root@nginx-server nginx-1.8.0]# make && make install#优化路径并检查:[root@nginx-server nginx-1.8.0]# ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/[root@nginx-server nginx-1.8.0]# nginx -tnginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is oknginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful#启动服务:[root@nginx-server nginx-1.8.0]# nginx[root@nginx-server nginx-1.8.0]# netstat -anput | grep nginxtcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 21416/nginx: master #开启防火墙的80端口:[root@nginx-server nginx-1.8.0]# firewall-cmd --add-port=80/tcp --permanentsuccess[root@nginx-server nginx-1.8.0]# firewall-cmd --reloadsuccess
2,安装php
1)安装依赖工具包:[root@php-server ~]# yum -y install gcc* pcre-devel openssl-devel zlib-devel libxml2-devel libcurl-devel bzip2-devel make vim
2)安装php的加密扩展模块libmcrypt[root@php-server ~]# tar zxf libmcrypt-2.5.7.tar.gz [root@php-server ~]# cd libmcrypt-2.5.7[root@php-server libmcrypt-2.5.7]# ./configure --prefix=/usr/local/libmcrypt && make && make install
3)安装php:[root@php-server ~]# tar zxf php-5.6.27.tar.gz[root@php-server ~]# cd php-5.6.27[root@php-server php-5.6.27]# ./configure --prefix=/usr/local/php5.6 --with-mysql=mysqlnd \> --with-pdo-mysql=mysqlnd --with-mysqli=mysqlnd --with-openssl --enable-fpm --enable-sockets \> --enable-sysvshm --enable-mbstring --with-freetype-dir --with-jpeg-dir --with-png-dir \> --with-zlib --with-libxml-dir=/usr --enable-xml --with-mhash --with-mcrypt=/usr/local/libmcrypt \> --with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d --with-bz2 --enable-maintainer-zts
配置参数解释:
--prefix=/usr/local/php7.2 #指定php的安装路径mysqlnd(mysql native driver)#php源码提供的mysql驱动连接代码--with-mysql=mysqlnd #支持mysql--with-pdo-mysql=mysqlnd #支持pdo模块,php执行命令通过pdo语法来连接后端的数据库--with-mysqli=mysqlnd #执行libmysql模块,也叫mysql的增强模块 --with-openssl #支持ssl --enable-fpm #开启php的进程管理器 --enable-sockets #开启socket支持,socket本职位编程接口(API) --enable-sysvshm #开启系统共享内存支持 --enable-mbstring #支持多字节字符串,如中文就是多字节字符串,一个汉字代表2个字节 --with-freetype-dir #支持freetype(字体引擎),需要借助freetype-devel,字体解析工具 --with-jpeg-dir #支持jepg和png图片,php在解析的过程会生成一些图像--with-png-dir --with-zlib #数据压缩用的函数库--with-libxml-dir=/usr #打开libxml2库支持的xml文件--enable-xml #开启xml文件传输 --with-mhash #支持mhash,mhash可用于创建校验数值,消息摘要,消息认证码,以及无需要原文等待关键信息保存(如密码)等 -with-mcrypt=/usr/local/libmcrypt #php中加密支持扩展库 --with-config-file-path=/etc #配置文件路径 --with-config-file-scan-dir=/etc/php.d #配置文件扫描路径 --with-bz2 #支持bzip2压缩 --enable-maintainer-zts #支持php多线程扩展
注意:在php7版本中,已经不支持的某些参数选项,比如上面-with-mcrypt和--with-mysql参数已经在7版本中废除了,如果用的是7版本,在配置时需要将上面两个编译选项删除就可以了。
#编译安装[root@php-server php-5.6.27]# make && make install#提供php配置文件:[root@php-server php-5.6.27]# cp php.ini-production /etc/php.ini#创建php-fpm服务启动脚本:[root@php-server php-5.6.27]# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm[root@php-server php-5.6.27]# chmod +x /etc/init.d/php-fpm #加入开机自启[root@php-server php-5.6.27]# chkconfig --add php-fpm[root@php-server php-5.6.27]# chkconfig php-fpm on#提供php-fpm配置文件并进行简单优化:[root@php-server php-5.6.27]# cp /usr/local/php5.6/etc/php-fpm.conf.default /usr/local/php5.6/etc/php-fpm.conf[root@php-server ~]# vim /usr/local/php5.6/etc/php-fpm.conf修改内容如下:pid = run/php-fpm.pid #pid文件的位置listen = 172.16.1.110:9000 #本机ip地址:端口pm.max_children = 300 #php创建的最大子进程pm.start_servers = 10 #启动时的子进程数量pm.min_spare_servers = 10 #最小空闲子进程pm.max_spare_servers =50 #最大空闲子进程#启动php服务:[root@php-server ~]# /etc/init.d/php-fpm startStarting php-fpm done[root@php-server ~]# netstat -anput | grep 9000tcp 0 0 172.16.1.110:9000 0.0.0.0:* LISTEN 3220/php-fpm: maste
#开启防火墙的9000端口:[root@php-server ~]# firewall-cmd --add-port=9000/tcp --permanentsuccess[root@php-server ~]# firewall-cmd --reloadsuccess
3,配置nginx与php动态解析
#配置nginx配置文件:
[root@nginx-server ~]# vim /usr/local/nginx/conf/nginx.conf
43 location / { 44 root html; 45 index index.html index.htm index.php #添加.php页面解析; 46 }
65 location ~ \.php$ { #表示匹配到php文件就进行fastcgi操作 66 root /usr/local/nginx/html; #用户请求的网页根目录 67 fastcgi_pass 172.16.1.110:9000; #指定解析php的ip地址+端口 68 fastcgi_index index.php; #默认代理的.php动态页面 69 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; #php解析的根目录 70 include fastcgi_params; 71 }
最后重启nginx服务使其生效。
#在php服务器上创建测试php测试文件:[root@php-server ~]# mkdir -p /usr/local/nginx/html[root@php-server ~]# cat /usr/local/nginx/html/test.php
#测试访问:
4,安装mysql
由于源码安装mysql过程太长,所以采用二进制进行安装。
#编写mysql一键安装脚本(并修改root密码):
[root@mysql-server ~]# cat mysql5.7.sh #!/bin/bashrpm -qa | grep mariadb &> /dev/nullif [ $? -eq 0 ]then rpm -e mariadb-libs --nodepsfitar zxf mysql-5.7.28-linux-glibc2.12-x86_64.tar.gz mv mysql-5.7.28-linux-glibc2.12-x86_64 /usr/local/mysqlln -s /usr/local/mysql/bin/* /usr/local/bingroupadd -r mysql && useradd -r -g mysql -s /bin/false -M mysqlmkdir /usr/local/mysql/datachown -R mysql:mysql /usr/local/mysqlcat > /etc/my.cnf <
#执行脚本进行安装,并查看验证mysql登录:
注:确保源码包和脚本在当前/root目录下。
[root@mysql-server ~]# sh mysql5.7.sh Starting MySQL.. SUCCESS! mysql: [Warning] Using a password on the command line interface can be insecure.[root@mysql-server ~]# netstat -anput | grep mysqldtcp6 0 0 :::3306 :::* LISTEN 15762/mysqld #开启防火墙的3306端口:[root@mysql-server ~]# firewall-cmd --add-port=3306/tcp --permanentsuccess[root@mysql-server ~]# firewall-cmd --reloadsuccess
二,安装配置memcache
1,安装memcached服务端
memcached 是基于 libevent 的事件处理。 libevent 是个程序库,它将 Linux 的 epoll、 BSD 类操作系统的 kqueue 等事件处理功能封装成统一的接口。memcached 使用这个 libevent 库,因此能在 Linux、 BSD、 Solaris 等操作系统上发挥其高性能。
1)首先安装memcached依赖库libevent:[root@memcached ~]# tar zxf libevent-2.0.22-stable.tar.gz [root@memcached ~]# cd libevent-2.0.22-stable[root@memcached libevent-2.0.22-stable]# ./configure && make && make install
2)安装memcached:[root@memcached ~]# tar zxf memcached-1.4.33.tar.gz [root@memcached ~]# cd memcached-1.4.33[root@memcached memcached-1.4.33]# ./configure --prefix=/usr/local/memcached --with-libevent=/usr/local && make && make install#配置环境变量:[root@memcached ~]# vim ~/.bash_profile添加:MEMCACHED_HOME=/usr/local/memcachedLD_LIBRARY_PATH=$LD_LIBRARY_PATH:$MEMCACHED_HOME/lib[root@memcached ~]# source ~/.bash_profile
3)启动memcached:[root@memcached ~]# ln -s /usr/local/memcached/bin/memcached /usr/local/sbin/[root@memcached ~]# memcached -d -m 2048 -l 172.16.1.130 -p 11211 -u root -c 102400 -P /usr/local/memcached/memcached.pid启动参数说明:-d 选项是启动一个守护进程-m 分配给memcached使用的内存数量,单位是MB,默认是64MB-l 监听的ip地址。(默认:INADDR_ANY,所有地址)-p 设置memcache的TCP监听端口,最好是1024以上的端口-u 运行memcache的用户,如果当前为root的话,需要使用此参数指定用户-c 选项是最大运行的并发连接数,默认是1024-P 设置保存memcache的pid文件-h 显示帮助[root@memcached ~]# netstat -anput | grep memcachedtcp 0 0 172.16.1.130:11211 0.0.0.0:* LISTEN 22916/memcached
#设置防火墙:[root@memcached ~]# firewall-cmd --add-port=11211/tcp --permanentsuccess[root@memcached ~]# firewall-cmd --reloadsuccess
2,安装memcache客户端(通常安装在php服务器上)
memcach分为服务端和客户端。服务端用来存放缓存,客户端用来操作缓存。
1)安装memcache扩展库:[root@php-server ~]# tar zxf memcache-3.0.8.tgz [root@php-server ~]# cd memcache-3.0.8[root@php-server memcache-3.0.8]# /usr/local/php5.6/bin/phpize Configuring for:PHP Api Version: 20131106Zend Module Api No: 20131226Zend Extension Api No: 220131226Cannot find autoconf. Please check your autoconf installation and the$PHP_AUTOCONF environment variable. Then, rerun this script.#根据上面的报错提示安装autoconf依赖包:[root@php-server memcache-3.0.8]# yum -y install autoconf#配置成功[root@php-server memcache-3.0.8]# /usr/local/php5.6/bin/phpize Configuring for:PHP Api Version: 20131106Zend Module Api No: 20131226Zend Extension Api No: 220131226[root@php-server memcache-3.0.8]# ./configure --enable-memcache --with-php-config=/usr/local/php5.6/bin/php-config[root@php-server memcache-3.0.8]# make && make install#安装成功后,会有这样的提示:Build complete.Don't forget to run 'make test'.Installing shared extensions: /usr/local/php5.6/lib/php/extensions/no-debug-zts-20131226/#安装成功,最后会显示memcache.so存放的路径。
#修改php.ini文件:[root@php-server memcache-3.0.8]# vi /etc/php.ini 添加一行:extension=/usr/local/php5.6/lib/php/extensions/no-debug-zts-20131226/memcache.so
#重启php服务并重新访问php页面:[root@php-server ~]# /etc/init.d/php-fpm restartGracefully shutting down php-fpm . doneStarting php-fpm done
#在php上创建测试代码,测试memcache客户端是否与服务端互相通信[root@php-server ~]# cat /usr/local/nginx/html/test2.php connect('172.16.1.130', 11211) or die ("Could not connect");$version = $memcache->getVersion();echo "Server's version: ".$version."
";$tmp_object = new stdClass;$tmp_object->str_attr = 'test';$tmp_object->int_attr = 123;$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");echo "Store data in the cache (data will expire in 10 seconds)
";$get_result = $memcache->get('key');echo "Data from the cache:
";var_dump($get_result);?>
#浏览器访问test2.php:
能够相互解析,memcache部署完毕。
三,使用memcache实现sessioin共享
#配置php.ini文件中的session共享:
[root@php-server ~]# vim /etc/php.ini
session.save_handler = memcache #设置存储数据方式以memcache方式存储(默认是以文件方式存储)#设置存储路径,通过tcp协议存储在memcache服务端上,多台memcache用逗号隔开session.save_path = "tcp://172.16.1.130:11211?persistent=1&weight=1&timeout=1&retry_interval=15"
参数解释:persistent:持久连接数量timeout=1:超时时间1秒钟retry_interval=15:15秒检查一次memcached服务器
#重启php[root@php-server ~]# /etc/init.d/php-fpm restartGracefully shutting down php-fpm . doneStarting php-fpm done
#测试memcache可用性:
编辑测试页面:[root@php-server ~]# cat /usr/local/nginx/html/memcache.php ";echo "now_time:".time()."
";echo "session_id:".session_id()."
";?>
#浏览器访问测试页面,可查看session_time是否都是为memcache中的Session,同时可以在不同的服务器上修改不同的标识查看是否为不同服务器上的(memcache集群)。
可以直接使用sessionid去memcached里查询一下:
[root@php-server ~]# yum -y install telnet [root@php-server ~]# telnet 172.16.1.130 11211 Trying 172.16.1.130...Connected to 172.16.1.130.Escape character is '^]'.get eg7rqdegogu0196brj7d973f95 #通过get获得该session_id的信息VALUE eg7rqdegogu0196brj7d973f95 0 26session_time|i:1583519270;END #输入quit退出
得到的session_time和在memcache客户端的session_time是一致的,说明session正常工作。
#默认memcache会监听11211端口,如果想清空服务器上memcache的缓存,一般使用flush_all命令,操作如下:[root@php-server ~]# telnet 172.16.1.130 11211Trying 172.16.1.130...Connected to 172.16.1.130.Escape character is '^]'.flush_allOK
注意:使用flush_all后并不是删除memcace上的key而是置为过期memcache安全配置。
四,memcache缓存数据库数据
1,在数据库中创建测试数据:
[root@mysql-server ~]# mysql -uroot -p123.com #在本地登录mysql #创建用户并授权(只给予连接和查询的权限):mysql> grant Usage,Select on *.* to test@'172.16.1.%' identified by '123.com';Query OK, 0 rows affected, 1 warning (0.00 sec) #创建库:mysql> create database testdb; Query OK, 1 row affected (0.00 sec)#创建表:mysql> create table testdb.testtb (id int primary key auto_increment, -> name varchar(20) default null) -> engine=innodb default charset=utf8; Query OK, 0 rows affected (0.28 sec)#插入数据:mysql> insert into testdb.testtb(name) values('tom1'),('tom2'),('tom3'),('tom4'),('tom5');Query OK, 5 rows affected (0.02 sec)Records: 5 Duplicates: 0 Warnings: 0
2,缓存测试
1)首先测试php能否与mysql沟通
[root@php-server ~]# cat /usr/local/nginx/html/mysql.php
#浏览器测试访问:
2) 测试memcache是否缓存数据库的数据
#编写测试脚本,内容如下:
[root@php-server html]# cat test_db.php connect($memcachehost,$memcacheport) or die ("Could not connect");$query="select * from testtb limit 10";$key=md5($query);if(!$memcache->get($key)){ $conn=mysql_connect("172.16.1.120","test","123.com"); mysql_select_db(testdb); $result=mysql_query($query);while ($row=mysql_fetch_assoc($result)) { $arr[]=$row; } $f = 'mysql'; $memcache->add($key,serialize($arr),0,30); $data = $arr ;}else{ $f = 'memcache'; $data_mem=$memcache->get($key); $data = unserialize($data_mem);}echo $f;echo "
";echo "$key";echo "
";//print_r($data);foreach($data as $a){echo "number is $a[id]";echo "
";echo "name is $a[name]";echo "
";}?>
访问页面测试
#第一次访问:
显示的是mysql表示memcached中没有内容,需要memcached从数据中取得。
#第二次访问:(刷新页面)
显示的是memcache标志,表示这次的数据是从memcached中取得的。
注意:memcached有个缓存时间默认是1分钟,过了一分钟后,memcached需要重新从数据库中取得数据。
#查看memcached缓存情况:
#使用telnet命令查看:
[root@php-server ~]# telnet 172.16.1.130 11211Trying 172.16.1.130...Connected to 172.16.1.130.Escape character is '^]'.stats #输入命令statsSTAT pid 22916 //memcached 进程的idSTAT uptime 9530 //进程运行时间STAT time 1583492752 //当前时间STAT version 1.4.33 //memcached版本STAT libevent 2.0.22-stableSTAT pointer_size 64STAT rusage_user 0.758872STAT rusage_system 1.264787STAT curr_connections 6STAT total_connections 19STAT connection_structures 7STAT reserved_fds 20STAT cmd_get 16 //总共获取数据的次数(等于get_hits+get_misses)STAT cmd_set 7 //总共设置数据的次数STAT cmd_flush 1STAT cmd_touch 0STAT get_hits 12 //命中了多少次数据(也就是从memcached缓存中成功获取数据的次数),命中率= get_hits/ cmd_getSTAT get_misses 4 //没有命中的次数STAT get_expired 2STAT get_flushed 0STAT delete_misses 0STAT delete_hits 0STAT incr_misses 1STAT incr_hits 0STAT decr_misses 0STAT decr_hits 0STAT cas_misses 0STAT cas_hits 0STAT cas_badval 0STAT touch_hits 0STAT touch_misses 0STAT auth_cmds 0STAT auth_errors 0STAT bytes_read 1864STAT bytes_written 3392STAT limit_maxbytes 2147483648 //总的存储大小,默认为为64MSTAT accepting_conns 1STAT listen_disabled_num 0STAT time_in_listen_disabled_us 0STAT threads 4STAT conn_yields 0STAT hash_power_level 16STAT hash_bytes 524288STAT hash_is_expanding 0STAT malloc_fails 0STAT log_worker_dropped 0STAT log_worker_written 0STAT log_watcher_skipped 0STAT log_watcher_sent 0STAT bytes 702 //当前所用存储大小STAT curr_items 4STAT total_items 7STAT expired_unfetched 0STAT evicted_unfetched 0STAT evictions 0STAT reclaimed 0STAT crawler_reclaimed 0STAT crawler_items_checked 0STAT lrutail_reflocked 0END
安装包已上传至百度网盘:链接:https://pan.baidu.com/s/1QcGj2Lj5hSZdxw_MuKTBoA
提取码:sph4