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 不需要編譯,只需要解壓就行。
[root@localhost ~]# tar zxf zlib-1.2.8.tar.gz
[root@localhost ~]# tar zxf pcre-8.39.tar.gz
2、安裝依賴包
[root@localhost ~]#yum -y install gcc gcc-c++ make libtool openssl openssl-devel
3、解壓源碼包
①下載 nginx 的源碼包: http://nginx.org/download
[root@localhost ~]# tar zxf nginx-1.14.0.tar.gz
[root@localhost ~]# cd nginx-1.14.0/
[root@localhost nginx-1.14.0]# groupadd www
[root@localhost nginx-1.14.0]# useradd -g www www -s /sbin/nologin
[root@localhost 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
[root@localhost nginx-1.14.0]# make && make install
[root@localhost nginx-1.14.0]# ln -s /usr/local/nginx1.14/sbin/nginx /usr/local/sbin/
[root@localhost 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
[root@localhost nginx-1.14.0]# nginx
[root@localhost nginx-1.14.0]# netstat -anpt | grep nginx
4、關閉防火墻或者開啟端口
[root@localhost nginx-1.14.0]# systemctl stop firewalld.service
5、安裝 php
①安裝 libmcrypt
[root@localhost ~]# tar zxf libmcrypt-2.5.7.tar.gz
[root@localhost ~]# cd libmcrypt-2.5.7/
[root@localhost libmcrypt-2.5.7]# ./configure --prefix=/usr/local/libmcrypt && make && make install
②安裝依賴包
[root@localhost libmcrypt-2.5.7]# yum -y install libxml2-devel libcurl-devel openssl-devel bzip2-devel
[root@localhost ~]# tar zxf php-5.6.27.tar.gz
[root@localhost ~]# cd php-5.6.27/
[root@localhost 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
[root@localhost php-5.6.27]#make && make install
[root@localhost php-5.6.27]# cp php.ini-production /etc/php.ini
③修改/etc/php.ini 文件,將 short_open_tag 修改為 on
[root@localhost php-5.6.27]#vim /etc/php.ini
;short_open_tag 改成 short_open_tag=0 //第151行(支持 php 短標簽 )
④創建 php-fpm 服務啟動腳本:
[root@localhost php-5.6.27]# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
[root@localhost php-5.6.27]# chmod +x /etc/init.d/php-fpm
[root@localhost php-5.6.27]# chkconfig --add php-fpm
[root@localhost php-5.6.27]# chkconfig php-fpm on
⑤提供 php-fpm 配置文件並編輯
[root@localhost php-5.6.27]# cp /usr/local/php5.6/etc/php-fpm.conf.default /usr/local/php5.6/etc/php-fpm.conf
[root@localhost 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 服務
[root@localhost php-5.6.27]# service php-fpm start
Starting php-fpm done
[root@localhost 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
[root@localhost ~]# tar zxf libevent-2.0.22-stable.tar.gz
[root@localhost ~]# cd libevent-2.0.22-stable/
[root@localhost libevent-2.0.22-stable]# ./configure
[root@localhost libevent-2.0.22-stable]# make && make install
①安裝 memcached
[root@localhost ~]# tar zxf memcached-1.4.33.tar.gz
[root@localhost ~]# cd memcached-1.4.33/
[root@localhost memcached-1.4.33]# ./configure --prefix=/usr/local/memcached --with-libevent=/usr/local
[root@localhost memcached-1.4.33]# make && make install
②檢測是否成功安裝
[root@localhost memcached-1.4.33]# ls /usr/local/memcached/bin/memcached
/usr/local/memcached/bin/memcached
③為系統環境變量 LD_LIBRARY_PATH 增加新的目錄
[root@localhost memcached-1.4.33]# vim ~/.bash_profile
添加:
MEMCACHED_HOME=/usr/local/memcached
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$MEMCACHED_HOME/lib
[root@localhost ~]# systemctl stop firewalld.service
[root@localhost ~]# /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
[root@localhost ~]# netstat -anpt |grep memcached
tcp 0 0 192.168.1.28:11211 0.0.0.0:* LISTEN 64362/memcached
④刷新用戶環境變量:
[root@localhost ~]# source ~/.bash_profile
⑤編寫 memcached 服務啟停腳本
[root@localhost 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
[root@localhost ~]# chmod +x /etc/init.d/memcached
[root@localhost ~]# chkconfig --add memcached
[root@localhost ~]# chkconfig memcached on
2、配置 nginx.conf 文件(在 nginx 主機操作)
①修改配置文件
[root@localhost ~]# 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 服務
[root@localhost php-5.6.27]# nginx -s reload
[root@localhost 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 測試頁
[root@localhost ~]# cd /usr/local/nginx1.14/html/
[root@localhost html]# vim test1.php
添加:
<?php
phpinfo();
?>
3、memcache 客戶端(在 nginx、php 服務器操作)
①安裝memcache客戶端
[root@localhost ~]# tar zxf memcache-3.0.8.tgz
[root@localhost ~]# cd memcache-3.0.8/
[root@localhost memcache-3.0.8]# /usr/local/php5.6/bin/phpize
[root@localhost memcache-3.0.8]#./configure --enable-memcache --with-php-config=/usr/local/php5.6/bin/php-config
[root@localhost memcache-3.0.8]# make && make install
②安裝完後會有類似這樣的提示:
Installing shared extensions:
/usr/local/php5.6/lib/php/extensions/no-debug-zts-20131226/
③把這個記住,然後修改 php.ini
[root@localhost memcache-3.0.8]# vim /etc/php.ini
添加:
extension=/usr/local/php5.6/lib/php/extensions/no-debug-zts-20131226/memcache.so
④重啟 php-fpm 服務
[root@localhost 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
④測試代碼:
[root@localhost memcache-3.0.8]# cd /usr/local/nginx1.14/html/
[root@localhost 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
[root@localhost 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 服務
[root@localhost memcache-3.0.8]# service php-fpm restart
③測試 memcache 可用性
在 nginx(php) 服務器上新建//usr/local/nginx1.10/html/memcache.php 文件
[root@localhost 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安裝
[root@localhost html]# yum -y install telnet
[root@localhost 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 服務器上創建測試表
[root@localhost ~]# 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 user@'%' identified by '123456';
Query OK, 0 rows affected, 1 warning (0.08 sec)
③在 nginx(php) 服務器上創建測試腳本內容
[root@localhost 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 緩存情況
[root@localhost ~]# 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)