memcache缓存服务器(nginx php memcache mysql)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了memcache缓存服务器(nginx php memcache mysql)相关的知识,希望对你有一定的参考价值。
memcache缓存服务器(nginx php memcache mysql)
环境:
192.168.1.23 nginx+php
192.168.1.28 memcache
192.168.1.27 mysql
一、安装 nginx (192.168.1.23)
1、解压 zlib 和pcre 不需要编译,只需要解压就行。
[[email protected] ~]# tar zxf zlib-1.2.8.tar.gz
[[email protected] ~]# tar zxf pcre-8.39.tar.gz
2、安装依赖包
[[email protected] ~]#yum -y install gcc gcc-c++ make libtool openssl openssl-devel
3、解压源码包
①下载 nginx 的源码包: http://nginx.org/download
[[email protected] ~]# tar zxf nginx-1.14.0.tar.gz
[[email protected] ~]# cd nginx-1.14.0/
[[email protected] nginx-1.14.0]# groupadd www
[[email protected] nginx-1.14.0]# useradd -g www www -s /sbin/nologin
[[email protected] nginx-1.14.0]#./configure --prefix=/usr/local/nginx1.14
--with-http_dav_module --with-http_stub_status_module
--with-http_addition_module --with-http_sub_module
--with-http_flv_module --with-http_mp4_module
--with-pcre=/root/pcre-8.39 --with-zlib=/root/zlib-1.2.8
--with-http_ssl_module --with-http_gzip_static_module --user=www
--group=www
[[email protected] nginx-1.14.0]# make && make install
[[email protected] nginx-1.14.0]# ln -s /usr/local/nginx1.14/sbin/nginx /usr/local/sbin/
[[email protected] nginx-1.14.0]# nginx -t
nginx: the configuration file /usr/local/nginx1.14/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx1.14/conf/nginx.conf test is successful
[[email protected] nginx-1.14.0]# nginx
[[email protected] nginx-1.14.0]# netstat -anpt | grep nginx
4、关闭防火墙或者开启端口
[[email protected] nginx-1.14.0]# systemctl stop firewalld.service
5、安装 php
①安装 libmcrypt
[[email protected] ~]# tar zxf libmcrypt-2.5.7.tar.gz
[[email protected] ~]# cd libmcrypt-2.5.7/
[[email protected] libmcrypt-2.5.7]# ./configure --prefix=/usr/local/libmcrypt && make && make install
②安装依赖包
[[email protected] libmcrypt-2.5.7]# yum -y install libxml2-devel libcurl-devel openssl-devel bzip2-devel
[[email protected] ~]# tar zxf php-5.6.27.tar.gz
[[email protected] ~]# cd php-5.6.27/
[[email protected] 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
[[email protected] php-5.6.27]#make && make install
[[email protected] php-5.6.27]# cp php.ini-production /etc/php.ini
③修改/etc/php.ini 文件,将 short_open_tag 修改为 on
[[email protected] php-5.6.27]#vim /etc/php.ini
;short_open_tag 改成 short_open_tag=0 //第151行(支持 php 短标签 )
④创建 php-fpm 服务启动脚本:
[[email protected] php-5.6.27]# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
[[email protected] php-5.6.27]# chmod +x /etc/init.d/php-fpm
[[email protected] php-5.6.27]# chkconfig --add php-fpm
[[email protected] php-5.6.27]# chkconfig php-fpm on
⑤提供 php-fpm 配置文件并编辑
[[email protected] php-5.6.27]# cp /usr/local/php5.6/etc/php-fpm.conf.default /usr/local/php5.6/etc/php-fpm.conf
[[email protected] php-5.6.27]#vim /usr/local/php5.6/etc/php-fpm.conf
第25行去掉; pid = run/php-fpm.pid
第164行 listen =127.0.0.1:9000
第235行 pm.max_children = 300
第240行 pm.start_servers = 10
第245行 pm.min_spare_servers = 10
第250行 pm.max_spare_servers =50
⑥启动 php-fpm 服务
[[email protected] php-5.6.27]# service php-fpm start
Starting php-fpm done
[[email protected] php-5.6.27]# netstat -anpt | grep php-fpm
tcp 0 0 127.0.0.1:9000 0.0.0.0:* LISTEN 52269/php-fpm: mast
二、安装MySQL省略(192.168.1.27)
三、安装 memcached 服务端 (192.168.1.28)
1、首先先安装 memcached 依赖库 libevent
[[email protected] ~]# tar zxf libevent-2.0.22-stable.tar.gz
[[email protected] ~]# cd libevent-2.0.22-stable/
[[email protected] libevent-2.0.22-stable]# ./configure
[[email protected] libevent-2.0.22-stable]# make && make install
①安装 memcached
[[email protected] ~]# tar zxf memcached-1.4.33.tar.gz
[[email protected] ~]# cd memcached-1.4.33/
[[email protected] memcached-1.4.33]# ./configure --prefix=/usr/local/memcached --with-libevent=/usr/local
[[email protected] memcached-1.4.33]# make && make install
②检测是否成功安装
[[email protected] memcached-1.4.33]# ls /usr/local/memcached/bin/memcached
/usr/local/memcached/bin/memcached
③为系统环境变量 LD_LIBRARY_PATH 增加新的目录
[[email protected] memcached-1.4.33]# vim ~/.bash_profile
添加:
MEMCACHED_HOME=/usr/local/memcached
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$MEMCACHED_HOME/lib
[[email protected] ~]# systemctl stop firewalld.service
[[email protected] ~]# /usr/local/memcached/bin/memcached -d -m 2048 -l 192.168.1.28 -p 11211 -u root -c 10240 -P /usr/local/memcached/memcached.pid
[[email protected] ~]# netstat -anpt |grep memcached
tcp 0 0 192.168.1.28:11211 0.0.0.0:* LISTEN 64362/memcached
④刷新用户环境变量:
[[email protected] ~]# source ~/.bash_profile
⑤编写 memcached 服务启停脚本
[[email protected] memcached-1.4.33]#vi /etc/init.d/memcached
添加:
#!/bin/sh
#
# pidfile: /usr/local/memcached/memcached.pid
# memcached_home: /usr/local/memcached
# chkconfig: 35 21 79
# description: Start and stop memcached Service
# Source function library
. /etc/rc.d/init.d/functions
RETVAL=0
prog="memcached"
basedir=/usr/local/memcached
cmd=${basedir}/bin/memcached
pidfile="$basedir/${prog}.pid"
#interface to listen on (default: INADDR_ANY, all addresses)
ipaddr="192.168.1.28"
#listen port
port=11211
#username for memcached
username="root"
#max memory for memcached,default is 64M
max_memory=2048
#max connections for memcached
max_simul_conn=10240
start() {
echo -n $"Starting service: $prog"
$cmd -d -m $max_memory -u $username -l $ipaddr -p $port -c $max_simul_conn -P $pidfile
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && touch /var/lock/subsys/$prog
}
stop() {
echo -n $"Stopping service: $prog "
run_user=$(whoami)
pidlist=$(ps -ef | grep $run_user | grep memcached | grep -v grep | awk '{print($2)}')
for pid in $pidlist
do
kill -9 $pidif [ $? -ne 0 ]; then
return 1
fi
done
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/$prog
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
*)
echo "Usage: $0 {start|stop|restart|status}"
exit 1
esac
exit $RETVAL
[[email protected] ~]# chmod +x /etc/init.d/memcached
[[email protected] ~]# chkconfig --add memcached
[[email protected] ~]# chkconfig memcached on
2、配置 nginx.conf 文件(在 nginx 主机操作)
①修改配置文件
[[email protected] ~]# vi /usr/local/nginx1.14/conf/nginx.conf
全删掉然后添加:
user www www;
worker_processes 2;
worker_cpu_affinity 01 10;
error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;pid logs/nginx.pid;
events {
use epoll;
worker_connections 65535;
multi_accept on;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
tcp_nopush on;
keepalive_timeout 65;
tcp_nodelay on;
client_header_buffer_size 4k;
open_file_cache max=102400 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 1;
client_header_timeout 15;
client_body_timeout 15;
reset_timedout_connection on;
send_timeout 15;
server_tokens off;
client_max_body_size 10m;
fastcgi_connect_timeout 600;
fastcgi_send_timeout 600;
fastcgi_read_timeout 600;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;
fastcgi_temp_path /usr/local/nginx1.14/nginx_tmp;
fastcgi_intercept_errors on;
fastcgi_cache_path /usr/local/nginx1.14/fastcgi_cache levels=1:2 keys_zone=cache_fastcgi:128m inactive=1d max_size=10g;
gzip on;
gzip_min_length 2k;
gzip_buffers 4 32k;
gzip_http_version 1.1;
gzip_comp_level 6;
gzip_types text/plain text/css text/javascript application/json application/javascript application/x-javascript application/xml;
gzip_vary on;
gzip_proxied any;
server {
listen 80;
server_name www.benet.com;
#charset koi8-r;
#access_log logs/host.access.log main;
location ~* ^.+.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
valid_referers none blocked www.benet.com benet.com;
if ($invalid_referer) {
#return 302 http://www.benet.com/img/nolink.jpg;
return 404;
break;
}
access_log off;
}
location / {
root html;
index index.php index.html index.htm;
}
location ~* .(ico|jpe?g|gif|png|bmp|swf|flv)$ {
expires 30d;
#log_not_found off;
access_log off;
}
location ~* .(js|css)$ {
expires 7d;
log_not_found off;
access_log off;
}location = /(favicon.ico|roboots.txt) {
access_log off;
log_not_found off;
}
location /status {
stub_status on;
}
location ~ .*.(php|php5)?$ {
root html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
fastcgi_cache cache_fastcgi;
fastcgi_cache_valid 200 302 1h;
fastcgi_cache_valid 301 1d;
fastcgi_cache_valid any 1m;
fastcgi_cache_min_uses 1;
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_cache_key http://$host$request_uri;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
②重启 nginx 服务
[[email protected] php-5.6.27]# nginx -s reload
[[email protected] php-5.6.27]# netstat -anpt | grep nginx
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 15512/nginx: worker
③生成一个 php 测试页
[[email protected] ~]# cd /usr/local/nginx1.14/html/
[[email protected] html]# vim test1.php
添加:
<?php
phpinfo();
?>
3、memcache 客户端(在 nginx、php 服务器操作)
①安装memcache客户端
[[email protected] ~]# tar zxf memcache-3.0.8.tgz
[[email protected] ~]# cd memcache-3.0.8/
[[email protected] memcache-3.0.8]# /usr/local/php5.6/bin/phpize
[[email protected] memcache-3.0.8]#./configure --enable-memcache --with-php-config=/usr/local/php5.6/bin/php-config
[[email protected] memcache-3.0.8]# make && make install
②安装完后会有类似这样的提示:
Installing shared extensions:
/usr/local/php5.6/lib/php/extensions/no-debug-zts-20131226/
③把这个记住,然后修改 php.ini
[[email protected] memcache-3.0.8]# vim /etc/php.ini
添加:
extension=/usr/local/php5.6/lib/php/extensions/no-debug-zts-20131226/memcache.so
④重启 php-fpm 服务
[[email protected] memcache-3.0.8]# service php-fpm restart
Gracefully shutting down php-fpm . done
Starting php-fpm done
4、测试:
①检查 php 扩展是否正确安装 查询结果中是否有 memcache 项
②创建 phpinfo()页面,查询 session 项下面的 Registered save handlers 值中是否有 memcache
项
③浏览器访问 test1.php
④测试代码:
[[email protected] memcache-3.0.8]# cd /usr/local/nginx1.14/html/
[[email protected] html]# vim test2.php
添加:
<?php
$memcache = new Memcache;
$memcache->connect('192.168.1.28', 11211) or die ("Could not connect");
$version = $memcache->getVersion();echo "Server's version: ".$version."<br/>";
$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)<br/>";
$get_result = $memcache->get('key');
echo "Data from the cache:<br/>";
var_dump($get_result);
?>
⑤浏览器访问 test2.ph
5、使用 memcache 实现 session 共享
①编辑php.ini
[[email protected] html]# vim /etc/php.ini
第1394行 session.save_handler = memcache
第1423行 session.save_path = "tcp://192.168.1.28:11211?persistent=1&weight=1&timeout=1&retry_interval=15"
②重启 php-fpm 服务
[[email protected] memcache-3.0.8]# service php-fpm restart
③测试 memcache 可用性
在 nginx(php) 服务器上新建//usr/local/nginx1.10/html/memcache.php 文件
[[email protected] html]# vim memcache.php
<?php
session_start();
if (!isset($_SESSION['session_time']))
{
$_SESSION['session_time'] = time();
}
echo "session_time:".$_SESSION['session_time']."<br />";
echo "now_time:".time()."<br />";echo "session_id:".session_id()."<br />";
?>
④访问网址 查看 session_time 是否都是为 memcache
中的 Session,同时可以在不同的服务器上修改不同的标识查看是否为不同的服务器
可以直接用 sessionid 去 memcached 里查询一下:
⑤没安装telnet可以yum安装
[[email protected] html]# yum -y install telnet
[[email protected] html]# telnet 192.168.1.28 11211
Trying 192.168.1.28...
Connected to 192.168.1.28.
Escape character is '^]'.
get r9k2ude5o7q92tb0772vlopee5
VALUE r9k2ude5o7q92tb0772vlopee5 0 26
session_time|i:1527087585;
END
得到 session_time|i:1527087585;这样的结果,说明 session 正常工作
默认 memcache 会监听 11221 端口,如果想清空服务器上 memecache 的缓存,一般使用:
Trying 192.168.1.28...
Connected to 192.168.1.28.
Escape character is '^]'.
flush_all
OK
6、测试 memcache 缓存数据库数据
①在 Mysql 服务器上创建测试表
[[email protected] ~]# mysql -uroot -p123456
mysql> create database testdb1;
Query OK, 1 row affected (0.07 sec)
mysql> use testdb1;
Database changed
mysql> create table test1(id int not null auto_increment,name varchar(20) default null,primarykey (id)) engine=innodb auto_increment=1 default charset=utf8;
Query OK, 0 rows affected (0.20 sec)
mysql> insert into test1(name) values ('tom1'),('tom2'),('tom3'),('tom4'),('tom5');
Query OK, 5 rows affected (0.09 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql> select * from test1;
+----+------+
| id | name |
+----+------+
| 1 | tom1 |
| 2 | tom2 |
| 3 | tom3 |
| 4 | tom4 |
| 5 | tom5 |
+----+------+
5 rows in set (0.00 sec)
②测试
创建php测试脚本 用于测试 memcache 是否缓存数据成功 需要为这个脚本添加一个只读的数据库用户
mysql> grant select on testdb1.* to [email protected]'%' identified by '123456';
Query OK, 0 rows affected, 1 warning (0.08 sec)
③在 nginx(php) 服务器上创建测试脚本内容
[[email protected] html]# vim test_db.php
添加:
<?php
$memcachehost = '192.168.1.28';
$memcacheport = 11211;
$memcachelife = 60;
$memcache = new Memcache;
$memcache->connect($memcachehost,$memcacheport) or die ("Could not connect");
$query="select * from test1 limit 10";
$key=md5($query);
if(!$memcache->get($key))
{
$conn=mysql_connect("192.168.1.27","user","123456");
mysql_select_db(testdb1);
$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 "<br>";
echo "$key";
echo "<br>";
//print_r($data);
foreach($data as $a)
{
echo "number is <b><font color=#FF0000>$a[id]</font></b>";
echo "<br>";
echo "name is <b><font color=#FF0000>$a[name]</font></b>";
echo "<br>";
}
?>
④访问页面测试
如果出现 mysql 表示 memcached 中没有内容,需要 memcached 从数据库中取得
再刷新页面, 如果有 memcache 标志表示这次的数据是从 memcached 中取得的。
memcached 有个缓存时间默认是 1 分钟,过了一分钟后, memcached 需要重新从数据库中
取得数据
⑤查看 Memcached 缓存情况
[[email protected] ~]# telnet 192.168.1.28 11211
Trying 192.168.1.28...
Connected to 192.168.1.28.
Escape character is '^]'.
stats
STAT pid 53181 //Memcached 进程的 ID
STAT uptime 3170 //进程运行时间
STAT time 1527088278 //当前时间
STAT version 1.4.33 // Memcached 版本
STAT libevent 2.0.22-stable
STAT pointer_size 64
STAT rusage_user 0.904999
STAT rusage_system 1.218613
STAT curr_connections 15
STAT total_connections 34
STAT connection_structures 16
STAT reserved_fds 20
STAT cmd_get 34 //总共获取数据的次数(等于 get_hits + get_misses )
STAT cmd_set 53 //总共设置数据的次数
STAT cmd_flush 1
STAT cmd_touch 0
STAT get_hits 27 //命中了多少次数据,也就是从 Memcached 缓存中成功获取数据的次数
STAT get_misses 7 //没有命中的次数
STAT get_expired 1
STAT get_flushed 0
STAT delete_misses 0
STAT delete_hits 0
STAT incr_misses 1
STAT incr_hits 12
STAT decr_misses 0
STAT decr_hits 0
STAT cas_misses 0
STAT cas_hits 0
STAT cas_badval 0
STAT touch_hits 0
STAT touch_misses 0
STAT auth_cmds 0
STAT auth_errors 0
STAT bytes_read 5521
STAT bytes_written 3502
STAT limit_maxbytes 2147483648 //总的存储大小,默认为 64M
STAT accepting_conns 1
STAT listen_disabled_num 0
STAT time_in_listen_disabled_us 0
STAT threads 4
STAT conn_yields 0
STAT hash_power_level 16
STAT hash_bytes 524288
STAT hash_is_expanding 0
STAT malloc_fails 0
STAT log_worker_dropped 0
STAT log_worker_written 0
STAT log_watcher_skipped 0
STAT log_watcher_sent 0
STAT bytes 702 //当前所用存储大小
STAT curr_items 4
STAT total_items 41
STAT expired_unfetched 0
STAT evicted_unfetched 0
STAT evictions 0
STAT reclaimed 1
STAT crawler_reclaimed 0
STAT crawler_items_checked 0
STAT lrutail_reflocked 0
END
命中率= get_hits/ cmd_get
以上是关于memcache缓存服务器(nginx php memcache mysql)的主要内容,如果未能解决你的问题,请参考以下文章
memcache缓存服务器(Nginx+PHP+memcache+MySQL)