memcache

memcache

1.       实验环境:

192.168.24.128   web+PHP

192.168.24.129   mysql

192.168.24.130   mem

关闭防火墙、selinux

1.       MemCache简介

MemCache 是一个自由、源码开放、高性能、分布式的分布式内存对象缓存系统,用于动态Web应用以减轻数据库的负载。它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高了网站访问的速度。 MemCaChe 是一个存储键值对的 HashMap,在内存中对任意的数据(比如字符串、对象等)所使用的 key-value 存储,数据可以来自数据库调用、API调用,或者页面渲染的结果。MemCache 设计理念就是小而强大,它简单的设计促进了快速部署、易于开发并解决面对大规模的数据缓存的许多难题,而所开放的 API 使得 MemCache

能用于 JavaC/C++/C#PerlPythonPHPRuby 等大部分流行的程序语言。

另外,说一下为什么会有 Memcache memcached 两种名称?其实 Memcache 是这个项目的名称,而 memcached 是它服务器端的主程序文件名

MemCache 的官方网站为 http://memcached.org/

1.       安装 nginx( 192.168.24.128 主机操作)

解压 zlib
[root@web src]# tar zxf zlib-1.2.8.tar.gz 
说明:不需要编译,只需要解压就行。

解压 pcre
[root@web src]# tar zxf pcre-8.39.tar.gz
说明:不需要编译,只需要解压就行。

[root@web src]# yum -y install gcc gcc-c++ make libtool openssl openssl-devel

下载 nginx 的源码包:http://nginx.org/download
解压源码包:

[root@web src]# tar zxf nginx-1.10.2.tar.gz 
[root@web src]# cd nginx-1.10.2/
[root@web nginx-1.10.2]# groupadd www     ##添加 www 组
[root@web nginx-1.10.2]# useradd -g www www -s /sbin/nologin     ##创建 nginx 运行账户 www 并加入到www 组,不允许 www 用户直接登录系统

[root@web nginx-1.10.2]# ./configure --prefix=/usr/local/nginx1.10 --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=/usr/local/src/pcre-8.39 --with-zlib=/usr/local/src/zlib-1.2.8 --with-http_ssl_module --with-http_gzip_static_module --user=www --group=www

[root@web nginx-1.10.2]# make && make install

[root@web nginx-1.10.2]# ln -s /usr/local/nginx1.10/sbin/nginx /usr/local/sbin/
[root@web nginx-1.10.2]# nginx -t
nginx: the configuration file /usr/local/nginx1.10/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx1.10/conf/nginx.conf test is successful
[root@web nginx-1.10.2]# nginx 
[root@web nginx-1.10.2]# netstat -anpt | grep nginx
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      23180/nginx: master

启动后可以再浏览器中打开页面,会显示 nginx 默认页面。


4.      安装 php

安装 libmcrypt
[root@web src]# tar zxf libmcrypt-2.5.7.tar.gz
[root@web src]# cd libmcrypt-2.5.7/
[root@web libmcrypt-2.5.7]# ./configure --prefix=/usr/local/libmcrypt && make && make install
[root@web libmcrypt-2.5.7]# yum -y install libxml2-devel libcurl-devel openssl-devel bzip2-devel

[root@web src]# tar zxf php-5.6.27.tar.gz 
[root@web src]# cd php-5.6.27/
[root@web 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@web php-5.6.27]# make && make install
[root@web php-5.6.27]# cp php.ini-production /etc/php.ini
修改/etc/php.ini 文件,将 short_open_tag 修改为 on,修改后的内容如下:
short_open_tag = On //支持 php 短标签
创建 php-fpm 服务启动脚本:
[root@web php-5.6.27]# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
[root@web php-5.6.27]# chmod +x /etc/init.d/php-fpm
[root@web php-5.6.27]# chkconfig --add php-fpm
[root@web php-5.6.27]# chkconfig php-fpm on

提供 php-fpm 配置文件并编辑:
[root@web php-5.6.27]# cp /usr/local/php5.6/etc/php-fpm.conf.default /usr/local/php5.6/etc/php-fpm.conf
[root@web php-5.6.27]# vim /usr/local/php5.6/etc/php-fpm.conf
pid = run/php-fpm.pid
listen =127.0.0.1:9000
pm.max_children = 300
pm.start_servers = 10
pm.min_spare_servers = 10
pm.max_spare_servers =50

启动 php-fpm 服务:
[root@web php-5.6.27]# service php-fpm start
Starting php-fpm  done
[root@web php-5.6.27]# netstat -anpt | grep php-fpm
tcp        0      0 127.0.0.1:9000          0.0.0.0:*               LISTEN      9718/php-fpm: maste

5.       安装 mysql(在 192.168.24.129 主机操作)

#这里使用的是脚本安装
#需要提前把mysql-5.7.20-linux-glibc2.12-x86_64.tar.gz放在/usr/local/src下
#!/bin/bash
rpm -e mariadb-libs --nodeps
tar zxf /usr/local/src/mysql-5.7.20-linux-glibc2.12-x86_64.tar.gz
mv /usr/local/src/mysql-5.7.20-linux-glibc2.12-x86_64 /usr/local/mysql
groupadd -r mysql
useradd -r -g mysql -s /sbin/false -M mysql
mkdir /usr/local/mysql/data
chown -R mysql:mysql /usr/local/mysql/
chmod 755 /usr/local/mysql/data/
echo "export PATH=$PATH:/usr/local/mysql/bin" >> /etc/profile
source /etc/profile
 cat << EOF > /etc/my.cnf
[client]
socket=/usr/local/mysql/mysql.sock
[mysqld]
basedir=/usr/local/mysql/
datadir=/usr/local/mysql/data
socket=/usr/local/mysql/mysql.sock
pid-file=/usr/local/mysql/mysqld.pid
log-error=/usr/local/mysql/mysql.err
EOF
cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
mysqld --initialize --user=mysql --basedir=/usr/local/mysql/data
service mysqld start
mysqlpw=`grep password /usr/local/mysql/mysql.err |awk -F "root@localhost: " '{print $2}'`
mysql -uroot -p$mysqlpw -e "alter user root@localhost identified by '123'" --connect-expired-password

6.       安装 memcached 服务端(在 192.168.24.130 主机操作)

memcached 是基于 libevent 的事件处理。libevent 是个程序库,它将 Linux epollBSD 类操作系统的 kqueue 等事件处理功能封装成统一的接口。即使对服务器的连接数增加,也能发挥 I/O 的性能。 memcached 使用这个 libevent 库,因此能在 LinuxBSDSolaris 等操作系统上发挥其高性能

首先先安装 memcached 依赖库 libevent
[root@mem src]# tar zxf libevent-2.0.22-stable.tar.gz 
[root@mem src]# cd libevent-2.0.22-stable/
[root@mem libevent-2.0.22-stable]# ./configure && make && make install

安装 memcached
[root@mem src]# tar zxf memcached-1.4.33.tar.gz 
[root@mem src]# cd memcached-1.4.33/
[root@mem memcached-1.4.33]# ./configure  --prefix=/usr/local/memcached --with-libevent=/usr/local
[root@mem memcached-1.4.33]# make && make install

检测是否成功安装
[root@mem memcached-1.4.33]# ls /usr/local/memcached/bin/memcached
/usr/local/memcached/bin/memcached

通过以上操作就很简单的把 memcached 服务端编译好了。这时候就可以打开服务端进行工作了。

配置环境变量:
进入用户宿主目录,编辑.bash_profile,为系统环境变量 LD_LIBRARY_PATH 增加新的目录,需要增加的内容如下:
[root@mem memcached-1.4.33]# vim ~/.bash_profile
MEMCACHED_HOME=/usr/local/memcached
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:MEMCACHED_HOME/lib

[root@mem memcached-1.4.33]# /usr/local/memcached/bin/memcached -d -m 2048 -l 192.168.24.130 -p 11211 -u root -c 10240 -P /usr/local/memcached/memcached.pid
[root@mem memcached-1.4.33]# netstat -anpt | grep memcached
tcp        0      0 192.168.24.130:11211    0.0.0.0:*               LISTEN      13626/memcached   

刷新用户环境变量:
[root@mem memcached-1.4.33]# source ~/.bash_profile

7.       配置 nginx.conf 文件(在 nginx 主机操作)

配置内容如下:

user www www;
worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;
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.10/nginx_tmp;
fastcgi_intercept_errors on;
fastcgi_cache_path  /usr/local/nginx1.10/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;
}
}
}
 检查配置文件:
[root@web conf]# nginx -t
nginx: the configuration file /usr/local/nginx1.10/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx1.10/conf/nginx.conf test is successful

重启 nginx 服务
生成一个 php 测试页
[root@web conf]# cat /usr/local/nginx1.10/html/test1.php
<?php
phpinfo();
?>

使用浏览器访问 test1.php 测试页


8.       memcache客户端(在 php 服务器操作):

memcache 分为服务端和客户端。服务端用来存放缓存,客户端用来操作缓存。

 

安装 php 扩展库(phpmemcache)。

安装 PHP Memcache 扩展:

可以使用 php 自带的 pecl 安装程序

# /usr/local/servers/php/bin/pecl install memcache

也可以从源码安装,他是生成 php 的扩展库文件 memcache.so

安装 memcache 扩展库
[root@web src]# tar zxf memcache-3.0.8.tgz 
[root@web src]# cd memcache-3.0.8/
[root@web memcache-3.0.8]# /usr/local/php5.6/bin/phpize
Configuring for:
PHP Api Version:         20131106
Zend Module Api No:      20131226
Zend Extension Api No:   220131226
[root@web memcache-3.0.8]# ./configure --enable-memcache --with-php-config=/usr/local/php5.6/bin/php-config
[root@web memcache-3.0.8]# make && make install

安装完后会有类似这样的提示:


把这个记住,然后修改 php.ini

添加一行

extension=/usr/local/php5.6/lib/php/extensions/no-debug-zts-20131226/memcache.so
重启 php-fpm 服务

[root@web memcache-3.0.8]# service php-fpm restart
Gracefully shutting down php-fpm . done
Starting php-fpm  done
	
测试:
检查 php 扩展是否正确安装
1、[root@www html]# /usr/local/php5.6/bin/php -m命令行执行 php -m 查询结果中是否有 memcache 项

2、创建 phpinfo()页面,查询 session 项下面的 Registered save handlers 值中是否有 memcache

 

浏览器访问test1.php



测试代码:

[root@web memcache-3.0.8]# cat /usr/local/nginx1.10/html/test2.php
<?php
$memcache = new Memcache;
$memcache->connect('192.168.24.130', 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.php


使用memcache 实现session 共享

配置 php.ini 中的 Session 为 memcache 方式。
session.save_handler = memcache
session.save_path = "tcp://192.168.24.130:11211?persistent=1&weight=1&timeout=1&retry_interval=15"

测试memcache 可用性

web 服务器上新建//usr/local/nginx1.10/html/memcache.php 文件。内容如下:

[root@web memcache-3.0.8]# cat /usr/local/nginx1.10/html/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 />";
?>

访问网址 http://192.168.24.128/memcache.php 可以查看 session_time 是否都是为 memcache中的 Session,同时可以在不同的服务器上修改不同的标识查看是否为不同的服务器上的。


可以直接用 sessionid memcached 里查询一下:


得到 session_time|i: 1525436266;这样的结果,说明 session 正常工作

默认 memcache 会监听 11221 端口,如果想清空服务器上 memecache 的缓存,一般使用的是:


同样也可以使用:


使用 flush_all 后并不是删除 memcache 上的 key,而是置为过期


memcache 安全配置

因为memcache不进行权限控制,因此需要通过iptablesmemcache仅开放个web服务器。

9.       测试 memcache 缓存数据库数据

Mysql 服务器上创建测试表

mysql> create database testdb1;
Query OK, 1 row affected (0.01 sec)

mysql> use testdb1;
Database changed
mysql> create table test1(id int not null auto_increment,name varchar(20) default null,primary key (id)) engine=innodb auto_increment=1 default charset=utf8;
Query OK, 0 rows affected (0.02 sec)

mysql> insert into test1(name) values ('tom1'),('tom2'),('tom3'),('tom4'),('tom5');
Query OK, 5 rows affected (0.03 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.00 sec)

web 服务器上创建测试脚本内容如下:

[root@web memcache-3.0.8]# cat /usr/local/nginx1.10/html/test_db.php
<?php
$memcachehost = '192.168.24.130';
$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.24.129","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 缓存情况

我们需要使用telnet 命令查看

[root@mem memcached-1.4.33]# telnet 192.168.24.130 11211
Trying 192.168.24.130...
Connected to 192.168.24.130.
Escape character is '^]'.
stats
STAT pid 13626			  //Memcached 进程的 ID
STAT uptime 4206		 //进程运行时间
STAT time 1525437454   //当前时间
STAT version 1.4.33     // Memcached 版本
STAT libevent 2.0.22-stable
STAT pointer_size 64
STAT rusage_user 0.602577
STAT rusage_system 1.010203
STAT curr_connections 5
STAT total_connections 33
STAT connection_structures 17
STAT reserved_fds 20
STAT cmd_get 40     //总共获取数据的次数(等于 get_hits + get_misses )
STAT cmd_set 43    //总共设置数据的次数
STAT cmd_flush 2
STAT cmd_touch 0
STAT get_hits 30    //命中了多少次数据,也就是从 Memcached 缓存中成功获取数据的次数
STAT get_misses 10    //没有命中的次数
STAT get_expired 2
STAT get_flushed 0
STAT delete_misses 0
STAT delete_hits 0
STAT incr_misses 2
STAT incr_hits 11
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 4464
STAT bytes_written 2481
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 234    //当前所用存储大小
STAT curr_items 2
STAT total_items 32
STAT expired_unfetched 3
STAT evicted_unfetched 0
STAT evictions 0
STAT reclaimed 4
STAT crawler_reclaimed 0
STAT crawler_items_checked 0
STAT lrutail_reflocked 0
END

命中率= get_hits/ cmd_get

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值