memcache缓存服务

MemCache 简介
MemCache 是一个自由、源码开放、高性能、分布式的分布式内存对象缓存系统,用于动态Web 应用以减轻数据库的负载。它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高了网站访问的速度。
memcache缓存服务
MemCache 的官方网站为 http://memcached.org/
MemCache 一次写缓存的流程:
1、应用程序输入需要写缓存的数据
2、 API 将 Key 输入路由算法模块,路由算法根据 Key 和 MemCache 集群服务器列表得到一台服务器编号
3、由服务器编号得到 MemCache 及其的 ip 地址和端口号
4、 API 调用通信模块和指定编号的服务器通信,将数据写入该服务器,完成一次分布式缓存的写操作读缓存和写缓存一样,只要使用相同的路由算法和服务器列表,只要应用程序查询的是相同的 Key, MemCache 客户端总是访问相同的客户端去读取数据,只要服务器中还缓存着该数据,就能保证缓存命中。
这种 MemCache 集群的方式也是从分区容错性的方面考虑的,假如 Node2 宕机了,那么Node2 上面存储的数据都不可用了,此时由于集群中 Node0 和 Node1 还存在,下一次请求Node2 中存储的 Key 值的时候,肯定是没有命中的,这时先从数据库中拿到要缓存的数据,然后路由算法模块根据 Key 值在 Node0 和 Node1 中选取一个节点,把对应的数据放进去,这样下一次就又可以走缓存了,这种集群的做法很好,但是缺点是成本比较大。
》 余数 Hash算法:用于固定的服务器,不适于扩展。
》一致性 Hash 算法:适于扩展。
MemCache 实现原理:
首先要说明一点, MemCache 的数据存放在内存中
1、访问数据的速度比传统的关系型数据库要快,因为 Oracle、 MySQL 这些传统的关系型数据库为了保持数据的持久性,数据存放在硬盘中, IO 操作速度慢
2、 MemCache 的数据存放在内存中同时意味着只要 MemCache 重启了,数据就会消失。
3、既然 MemCache 的数据存放在内存中,那么势必受到机器位数的限制, 32 位机器最多只能使用 2GB 的内存空间, 64 位机器可以认为没有上限。
然后我们来看一下 MemCache 的原理, MemCache 最重要的是内存如何分配的, MemCache采用的内存分配方式是固定空间分配, 如下图所示:
memcache缓存服务
这张图片里面涉及了 slab_class、 slab、 page、 chunk 四个概念,它们之间的关系是:
1、 MemCache 将内存空间分为一组 slab
2、每个 slab 下又有若干个 page,每个 page 默认是 1M,如果一个 slab 占用 100M 内存的话,那么这个 slab 下应该有 100 个 page
3、每个 page 里面包含一组 chunk, chunk 是真正存放数据的地方,同一个 slab 里面的 chunk的大小是固定的
4、有相同大小 chunk 的 slab 被组织在一起,称为 slab_class,MemCache 内存分配的方式称为 allocator(分配运算), slab 的数量是有限的,几个、十几个
或者几十个,这个和启动参数的配置相关。

Memcache 的工作流程:
memcache缓存服务
1、检查客户端的请求数据是否在 memcached 中,如果有,直接把请求数据返回,不再对数据库进行任何操作,路径操作为①②③⑦。
2、如果请求的数据不在 memcached 中,就去查数据库,把从数据库中获取的数据返回给客户端,同时把数据缓存一份到 memcached 中( memcached 客户端不负责,需要程序明确实现),路径操作为①②④⑤⑦⑥。
3、每次更新数据库的同时更新 memcached 中的数据,保证一致性。
4、当分配给 memcached 内存空间用完之后,会使用 LRU( Least Recently Used,最近最少使用)策略加上到期失效策略,失效数据首先被替换,然后再替换掉最近未使用的数据。
实验部署:
centos7.2+nginx+php+memcache+mysql
memcache缓存服务
nginx 和 php:
nginx-1.10.2.tar.gz
php-5.6.27.tar.gz
ip 地址: 192.168.159.21/24
memcache:
memcached-1.4.33.tar.gz
ip 地址: 192.168.159.22/24
mysql:
mysql-5.7.13.tar.gz
ip 地址: 192.168.159.23/24
安装 nginx(在 192.168.159.21 主机操作)
解压 zlib 、pcre(我用的zlib-1.2.8.tar pcre-8.39.tar)
注:不需要编译,只需要解压就行。
memcache缓存服务
然后yum安装依赖包
yum -y install gcc gcc-c++ make libtool openssl openssl-devel
memcache缓存服务
安装nginx
memcache缓存服务
groupadd www #添加 www 组
useradd -g www www -s /sbin/nologin #创建 nginx 运行账户 www 并加入到www 组,不允许 www 用户直接登录系统
配置一些模块:
./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=/root/pcre-8.39 --with-zlib=/root/zlib-1.2.8 --with-http_ssl_module --with-http_gzip_static_module
--user=www --group=www
memcache缓存服务
编译安装 make && make install
完成后:软连接优化
ln -s /usr/local/nginx1.10/sbin/nginx /usr/local/sbin/
memcache缓存服务
(红色箭头,说明成功,OK)
启动 nginx
nginx
查看端口:
netstat -anpt|grep nginx
tcp 0 0 0.0.0.0:80 0.0.0.0: LISTEN 61127/nginx: master
防火墙开启的添加端口
[root@nginx nginx-1.10.2]# firewall-cmd --permanent --add-port=80/tcp
[root@nginx nginx-1.10.2]# firewall-cmd --reload
memcache缓存服务
启动后可以再浏览器中打开页面,会显示 nginx 默认页面。
memcache缓存服务
安装 php
先安装依赖包:libmcrypt
[root@nginx ~]# tar zxf libmcrypt-2.5.7.tar.gz
[root@nginx ~]# cd libmcrypt-2.5.7/
[root@nginx libmcrypt-2.5.7]# ./configure --prefix=/usr/local/libmcrypt && make && make install
[root@nginx ~]# yum -y install libxml2-devel libcurl-devel openssl-devel bzip2-devel
[root@nginx 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@nginx php-5.6.27]# make && make install
[root@nginx 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@nginx php-5.6.27]# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
[root@nginx php-5.6.27]# chmod +x /etc/init.d/php-fpm
[root@nginx php-5.6.27]# chkconfig --add php-fpm
[root@nginx php-5.6.27]# chkconfig php-fpm on
提供 php-fpm 配置文件并编辑:
[root@nginx ~]# cd /usr/local/php5.6/etc/
[root@nginx etc]# cp php-fpm.conf.default php-fpm.conf
[root@nginx etc]# vim 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@nginx etc]# systemctl start php-fpm
[root@nginx etc]# netstat -antp|grep php-fpm
tcp 0 0 127.0.0.1:9000 0.0.0.0:
LISTEN 65010/php-fpm: mast
安装 mysql(在 192.168.159.23 主机操作)【我用的是二进制安装mysql-5.7.20】
编写MySQL安装脚本
内容如下:
#!/bin/bash
tar zxf mysql-5.7.20-linux-glibc2.12-x86_64.tar.gz
mv mysql-5.7.20-linux-glibc2.12-x86_64 /usr/local/mysql
rpm -e mariadb-libs --nodeps
groupadd mysql
useradd -g mysql -s /bin/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
echo "[client]" >> /etc/my.cnf
sed -i '1a socket=/tmp/mysql.sock \
[mysqld] \
user=mysql \
basedir=/usr/local/mysql \
datadir=/usr/local/mysql/data \
pid-file=/usr/local/mysql/data/mysql.pid \
socket=/tmp/mysql.sock \
log-error=/usr/local/mysql/data/mysql.err ' /etc/my.cnf
/usr/local/mysql/bin/mysqld --initialize --user=mysql --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data
export defaultmysqlpwd=grep 'A temporary password' /usr/local/mysql/data/mysql.err | awk -F"root@localhost: " '{ print $2}'
cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
service mysqld start
systemctl stop firewalld.service
systemctl disable firewalld.service
/usr/local/mysql/bin/mysql -uroot -p${defaultmysqlpwd} -e "alter user root@'localhost' identified by '123'" --connect-expired-password :wq
[root@mysql ~]# chmod +x mysql.sh
[root@mysql ~]# ./mysql.sh
做个软连接优化路径
[root@mysql ~]# ln -s /usr/local/mysql/bin/ /usr/local/bin/
安装 memcached 服务端(在 192.168.159.22 主机操作)
memcached 是基于 libevent 的事件处理。 libevent 是个程序库,它将 Linux 的 epoll、 BSD 类操作系统的 kqueue 等事件处理功能封装成统一的接口。即使对服务器的连接数增加,也能发挥 I/O 的性能。 memcached 使用这个 libevent 库,因此能在 Linux、 BSD、 Solaris 等操作系统上发挥其高性能。
首先先安装 memcached 依赖库 libevent
[root@memcache ~]# tar zxf libevent-2.0.22-stable.tar.gz
[root@memcache ~]# cd libevent-2.0.22-stable/
[root@memcache libevent-2.0.22-stable]# ./configure
[root@memcache libevent-2.0.22-stable]# make && make install
安装 memcached
root@memcache ~]# tar zxf memcached-1.4.33.tar.gz
[root@memcache ~]# cd memcached-1.4.33/
[root@memcache memcached-1.4.33]# ./configure --prefix=/usr/local/memcached --with-libevent=/usr/local
[root@memcache memcached-1.4.33]# make && make install
检测是否成功安装
[root@memcache memcached-1.4.33]# ls /usr/local/memcached/bin/memcached
/usr/local/memcached/bin/memcached
通过以上操作就很简单的把 memcached 服务端编译好了。这时候就可以打开服务端进行工作了。
配置环境变量::
进入用户宿主目录,编辑.bash_profile,为系统环境变量 LD_LIBRARY_PATH 增加新的目录,需要增加的内容如下:
[root@memcache memcached-1.4.33]# vim ~/.bash_profile
MEMCACHED_HOME=/usr/local/memcached
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$MEMCACHED_HOME/lib
[root@memcache memcached-1.4.33]# /usr/local/memcached/bin/memcached -d -m 2048 -l 192.168.159.22 -p 11211 -u root -c 10240 -P /usr/local/memcached /memcached.pid
启动参数说明:
-d 选项是启动一个守护进程。
-m 分配给 Memcache 使用的内存数量,单位是 MB,默认 64MB。
-l 监听的 IP 地址。(默认: INADDR_ANY,所有地址)
-p 设置 Memcache 的 TCP 监听的端口,最好是 1024 以上的端口。
-u 运行 Memcache 的用户,如果当前为 root 的话,需要使用此参数指定用户。
-c 选项是最大运行的并发连接数,默认是 1024。
-P 设置保存 Memcache 的 pid 文件。
-M 内存耗尽时返回错误,而不是删除项
-f 块大小增长因子,默认是 1.25
-n 最小分配空间, key+value+flags 默认是 48
-h 显示帮助
[root@memcache memcached-1.4.33]# netstat -anpt|grep memcached
tcp 0 0 192.168.159.22:11211 0.0.0.0:
LISTEN 51096/memcached
设置防火墙:
[root@memcache memcached-1.4.33]# firewall-cmd --permanent --add-port=11211/tcp
success
[root@memcache memcached-1.4.33]# firewall-cmd --reload
success
刷新用户环境变量:
[root@memcache ~]# source ~/.bash_profile
编写 memcached 服务启停脚本:
[root@memcache ~]# 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.31.250"
#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" / -n 不换行输出
$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 $pid
if [ $? -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@memcache ~]# chmod +x /etc/init.d/memcached
[root@memcache ~]# chkconfig --add memcached
[root@memcache ~]# chkconfig memcached on

配置 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;
}
}
}
重启 nginx 服务
[root@nginx 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
[root@nginx conf]# nginx -s reload
[root@nginx conf]# cd ../html/
[root@nginx html]# vim benet.php
<?php
phpinfo();
?>
生成一个 php 测试页
memcache缓存服务

memcache 客户端(在 php 服务器操作) :
memcache 分为服务端和客户端。服务端用来存放缓存,客户端用来操作缓存。
安装 php 扩展库( phpmemcache)。
安装 PHP Memcache 扩展:
可以使用 php 自带的 pecl 安装程序
[root@nginx ~]# /usr/local/php5.6/bin/pecl install memcache
也可以从源码安装,他是生成 php 的扩展库文件 memcache.so。
安装 memcache 扩展库
[root@nginx ~]# tar zxf memcache-3.0.8.tgz
[root@nginx ~]# cd memcache-3.0.8/
[root@nginx 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@nginx memcache-3.0.8]# ./configure --enable-memcache --with-php-config=/usr/local/php5.6/bin/php-config
[root@nginx memcache-3.0.8]# make && make install
安装完后会有类似这样的提示:
Installing shared extensions: /usr/local/php5.6/lib/php/extensions/no-debug-zts-20131226/
把这个记住,然后修改 php.ini
添加一行
extension= /usr/local/php5.6/lib/php/extensions/no-debug-zts-20131226/memcache.so
重启 php-fpm 服务
[root@nginx memcache-3.0.8]# service php-fpm restart
Gracefully shutting down php-fpm . done
Starting php-fpm done
测试:
检查 php 扩展是否正确安装
memcache缓存服务
命令行执行 php -m 查询结果中是否有 memcache 项
创建 phpinfo()页面,查询 session 项下面的 Registered save handlers 值中是否有 memcache项
浏览器访问 :benet1.php
memcache缓存服务
memcache缓存服务
测试代码:
[root@nginx html]# cat test2.php
<?php
$memcache = new Memcache;
$memcache->connect('192.168.159.22', 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);
?>
memcache缓存服务
使用 memcache 实现 session 共享
配置 php.ini 中的 Session 为 memcache 方式。
session.save_handler = memcache
session.save_path = "tcp://192.168.159.22:11211?persistent=1&weight=1&timeout=1&retry_interval=15"
注:session.save_handler: 设置 session 的储存方式为 memcache 。 默认以文件方式存取 session
数据,如果想要使用自定义的处理来存取 session 数据,比如 memcache 方式则修为session.save_handler = memcache
session.save_path: 设置 session 储存的位置,多台 memcache 用逗号隔开
使用多个 memcached server 时用逗号”,”隔开,可以带额外的参数”persistent”、”weight”、”timeout”、” retry_interval”等等,类似这样的: "tcp://host:port?persistent=1&weight=2,tcp://host2:port2"。
memcache 实现 session 共享也可以在某个一个应用中设置:
ini_set("session.save_handler", "memcache");
ini_set("session.save_path", "tcp://192.168.0.9:11211");
ini_set()只对当前 php 页面有效,并且不会去修改 php.ini 文件本身,也不会影响其他 php 页面。

测试 memcache 可用性
[root@nginx html]# cat 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 />";
?>
memcache缓存服务
可以直接用 sessionid 去 memcached 里查询一下:
[root@nginx html]# telnet 192.168.159.22 11211
Trying 192.168.159.22...
Connected to 192.168.159.22.
Escape character is '^]'.
get 7s6vidk4015q1u260kgmkpu3h5
VALUE 7s6vidk4015q1u260kgmkpu3h5 0 26
session_time|i:1500114087;
END
得到 session_time|i:1479134997;这样的结果,说明 session 正常工作
默认 memcache 会监听 11221 端口,如果想清空服务器上 memecache 的缓存,一般使用的是:
[root@memcache ~]# telnet 192.168.159.22 11211
Trying 192.168.159.22...
Connected to 192.168.159.22.
Escape character is '^]'.
flush_all
OK
同样也可以使用:
[root@memcache ~]# echo "flush_all | nc 192.168.159.22 11211"
使用 flush_all 后并不是删除 memcache 上的 key,而是置为过期memcache 安全配置因为 memcache 不进行权限控制,因此需要通过 iptables 将 memcache 仅开放个 web 服务器。
测试 memcache 缓存数据库数据
在 Mysql 服务器上创建测试表
mysql> create database testdb1;
Query OK, 1 row affected (0.04 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.06 sec)

mysql> insert into test1(name) values ('tom1'),('tom2'),('tom3'),('tom4'),('tom5');
Query OK, 5 rows affected (0.04 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)
mysql> grant select on testdb1.
to user@'%' identified by '123';
Query OK, 0 rows affected, 1 warning (0.02 sec)
用于测试 memcache 是否缓存数据成功需要为这个脚本添加一个只读的数据库用户
[root@nginx html]# cat mysql.php
<?php
$memcachehost = '192.168.159.22';
$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.159.23","user","123");
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>";
}
?>
memcache缓存服务
如果出现 mysql 表示 memcached 中没有内容,需要 memcached 从数据库中取得再刷新页面, 如果有 memcache 标志表示这次的数据是从 memcached 中取得的。
memcached 有个缓存时间默认是 1 分钟,过了一分钟后, memcached 需要重新从数据库中取得数据。

查看 Memcached 缓存情况
我们需要使用 telnet 命令查看
[root@memcache ~]# telnet 192.168.159.22 11211
Trying 192.168.159.22...
Connected to 192.168.159.22.
Escape character is '^]'.
stats
STAT pid 51096 //Memcached 进程的 ID
STAT uptime 4308 //进程运行时间
STAT time 1500115104 //当前时间
STAT version 1.4.33 // Memcached 版本
STAT libevent 2.0.22-stable
STAT pointer_size 64
STAT rusage_user 0.659560
STAT rusage_system 1.309422
STAT curr_connections 6
STAT total_connections 11
STAT connection_structures 8
STAT reserved_fds 20
STAT cmd_get 4 //总共获取数据的次数(等于 get_hits + get_misses )
STAT cmd_set 5 //总共设置数据的次数
STAT cmd_flush 1
STAT cmd_touch 0
STAT get_hits 2 //命中了多少次数据,也就是从 Memcached 缓存中成功获取数据的次数
STAT get_misses 2 //没有命中的次数
STAT get_expired 0
STAT get_flushed 0
STAT delete_misses 0
STAT delete_hits 0
STAT incr_misses 1
STAT incr_hits 0
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 750
STAT bytes_written 249
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 5
STAT expired_unfetched 0
STAT evicted_unfetched 0
STAT evictions 0
STAT reclaimed 0
STAT crawler_reclaimed 0
STAT crawler_items_checked 0
STAT lrutail_reflocked 0
END
命中率= get_hits/ cmd_get

转载于:https://blog.51cto.com/12620785/2063435

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值