大纲
一、什么是memcached
二、memcached特性
三、memcached存储方式
四、memcached安装与配置
五、memcached结合php
六、Nginx整合memcached
七、保存php session于memcached中
八、MemAdmin实现memcached的管理和监控
一、什么是memcached
Memcached是一款开源、高性能、分布式内存对象缓存系统,可应用各种需要缓存的场景,其主要目的是通过降低对Database的访问来加速web应用程序。它是一个基于内存的“键值对”存储,用于存储数据库调用、API调用或页面引用结果的直接数据,如字符串、对象等。
它是缓存服务器,但本身无法决定缓存任何数据,一半依赖于客户端,一半依赖于服务器,它自身只提供存储能力,但存储哪些数据,如何存是由客户端决定的。
二、memcached特点
memcached作为高速运行的分布式缓存服务器,具有以下的特点
-
简单key/value存储:服务器不关心数据本身的意义及结构,只要是可序列化数据即可。存储项由“键、过期时间、可选的标志及数据”四个部分组成;
-
功能的实现一半依赖于客户端,一半基于服务器端:客户负责发送存储项至服务器端、从服务端获取数据以及无法连接至服务器时采用相应的动作;服务端负责接收、存储数据,并负责数据项的超时过期;
-
各服务器间彼此无视:不在服务器间进行数据同步;
-
O(1)的执行效率
-
清理超期数据:默认情况下,Memcached是一个LRU缓存,同时,它按事先预订的时长清理超期数据;但事实上,memcached不会删除任何已缓存数据,只是在其过期之后不再为客户所见;而且,memcached也不会真正按期限清理缓存,而仅是当get命令到达时检查其时长;
补充:libevent是个程序库,它将Linux的epoll、BSD类操作系统的kqueue等事件处理功能封装成统一的接口。即使对服务器的连接数增加,也能发挥O(1)的性能。memcached使用这个libevent库,因此能在Linux、BSD、Solaris等操作系统上发挥其高性能。
三、memcached存储方式
为了提高性能,memcached中保存的数据都存储在memcached内置的内存存储空间中。由于数据仅存在于内存中,因此重启memcached、重启操作系统会导致全部数据消失。另外,内容容量达到指定值之后,就基于LRU(Least Recently Used)算法自动删除不使用的缓存。memcached本身是为缓存而设计的服务器,因此并没有过多考虑数据的永久性问题。
四、memcached安装与配置
系统环境
CentOS5.8 x86_64
软件包
memcached-1.4.5-1.el5.x86_64.rpm
libevent-1.4.13-1.el5.x86_64.rpm
1、首先配置好epel源
1
2
|
[root@soysauce ~]
# wget -P /etc/yum.repos.d/ http://mirrors.aliyun.com/repo/epel-5.repo
[root@soysauce ~]
# yum repolist
|
2、安装memcached
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
memcached是依赖于libevent API,如果是编译安装memcached,请确保libevent已经安装
[root@soysauce ~]
# yum install -y memcached
查看生成的文件
[root@soysauce ~]
# rpm -ql memcached
/etc/rc
.d
/init
.d
/memcached
/etc/sysconfig/memcached
/usr/bin/memcached
/usr/bin/memcached-tool
/usr/share/doc/memcached-1
.4.5
/usr/share/doc/memcached-1
.4.5
/AUTHORS
/usr/share/doc/memcached-1
.4.5
/CONTRIBUTORS
/usr/share/doc/memcached-1
.4.5
/COPYING
/usr/share/doc/memcached-1
.4.5
/ChangeLog
/usr/share/doc/memcached-1
.4.5
/NEWS
/usr/share/doc/memcached-1
.4.5
/README
/usr/share/doc/memcached-1
.4.5
/protocol
.txt
/usr/share/doc/memcached-1
.4.5
/readme
.txt
/usr/share/doc/memcached-1
.4.5
/threads
.txt
/usr/share/man/man1/memcached
.1.gz
/var/run/memcached
|
3、memcached常用选项说明
1
2
3
4
5
6
7
8
9
10
11
12
|
-l <ip_addr>:指定进程监听的地址;
-d: 以服务模式运行;
-u <username>:以指定的用户身份运行memcached进程;
-m <num>:用于缓存数据的最大内存空间,单位为MB,默认为64MB;
-c <num>:最大支持的并发连接数,默认为1024;
-p <num>: 指定监听的TCP端口,默认为11211;
-U <num>:指定监听的UDP端口,默认为11211,0表示关闭UDP端口;
-t <threads>:用于处理入站请求的最大线程数,仅在memcached编译时开启了支持线程才有效;
-f <num>:设定Slab Allocator定义预先分配内存空间大小固定的块时使用的增长因子;
-M:当内存空间不够使用时返回错误信息,而不是按LRU算法利用空间;
-n: 指定最小的slab chunk大小;单位是字节;
-S: 启用sasl进行用户认证;
|
4、启动memcached服务
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
[root@soysauce ~]
# service memcached start
Starting memcached: [ OK ]
[root@soysauce ~]
# netstat -tnlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID
/Program
name
tcp 0 0 127.0.0.1:9000 0.0.0.0:* LISTEN 30266
/php-fpm
tcp 0 0 0.0.0.0:11211 0.0.0.0:* LISTEN 5788
/memcached
tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN 2820
/portmap
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 25126
/sshd
tcp 0 0 127.0.0.1:6010 0.0.0.0:* LISTEN 5738
/sshd
tcp 0 0 0.0.0.0:922 0.0.0.0:* LISTEN 2860
/rpc
.statd
tcp 0 0 :::3306 :::* LISTEN 5669
/mysqld
tcp 0 0 :::11211 :::* LISTEN 5788
/memcached
tcp 0 0 :::22 :::* LISTEN 25126
/sshd
tcp 0 0 ::1:6010 :::* LISTEN 5738
/ssh
|
5、memcached相关命令
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
首先连接memcached
[root@soysauce ~]
# telnet localhost 11211
Trying 127.0.0.1...
Connected to localhost.localdomain (127.0.0.1).
Escape character is
'^]'
.
查看状态统计信息
stats
STAT pid 5788
STAT uptime 25
STAT
time
1453373921
STAT version 1.4.5
STAT pointer_size 64
STAT rusage_user 0.000000
STAT rusage_system 0.011998
STAT curr_connections 10
STAT total_connections 11
STAT connection_structures 11
STAT cmd_get 0
STAT cmd_set 0
STAT cmd_flush 0
STAT get_hits 0
STAT get_misses 0
STAT delete_misses 0
STAT delete_hits 0
STAT incr_misses 0
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 auth_cmds 0
STAT auth_errors 0
STAT bytes_read 9
STAT bytes_written 7
STAT limit_maxbytes 67108864
STAT accepting_conns 1
STAT listen_disabled_num 0
STAT threads 4
STAT conn_yields 0
STAT bytes 0
STAT curr_items 0
STAT total_items 0
STAT evictions 0
STAT reclaimed 0
END
添加一个新键
格式:add keyname flag timeout datasize
如:
add mykey 0 30 8
soysauce
STORED
获取某个键对应的值
格式:get keyname
如
get mykey
VALUE mykey 0 8
soysauce
END
|
附memcached常用命令列表
五、memcached结合php
1、编辑nginx配置文件,启用如下选项
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
[root@soysauce ~]
# vim /etc/nginx/nginx.conf
location ~ \.php$ {
root html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME
/scripts
$fastcgi_script_name;
include fastcgi_params;
}
主页添加.php支持
location / {
root html;
index index.php index.html index.htm;
}
|
2、编辑/etc/nginx/fastcgi_params,将其内容更改为如下内容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
[root@soysauce nginx]
# vim /etc/nginx/fastcgi_params
fastcgi_param GATEWAY_INTERFACE CGI
/1
.1;
fastcgi_param SERVER_SOFTWARE nginx;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;
fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;
|
3、重新载入nginx服务
1
2
3
4
5
6
7
|
[root@soysauce nginx]
# nginx -t
nginx: the configuration
file
/etc/nginx/nginx
.conf syntax is ok
nginx: configuration
file
/etc/nginx/nginx
.conf
test
is successful
[root@soysauce nginx]
# service nginx reload
nginx: the configuration
file
/etc/nginx/nginx
.conf syntax is ok
nginx: configuration
file
/etc/nginx/nginx
.conf
test
is successful
Reloading nginx: [ OK ]
|
4、测试是否能够支持php
1
2
3
4
|
[root@soysauce nginx]
# cat > /usr/html/index.php << EOF
> <?php
> phpinfo();
> ?>
|
到此,Nginx结合php能够正常工作,接下来我们来为php添加memcache扩展
5、安装memcache扩展
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
PHP有两个memcache客户端:php memcache和php memcached
memcache大概是04年出现的,功能较为简单
memcached大概是09年出现的,基于原生的c的libmemcached的扩展,更加完善,功能更加强大
这里以memcache作为演示,编译安装memcached,先下载源码包
[root@soysauce ~]
# wget https://pecl.php.net/get/memcache-2.2.5.tgz
[root@soysauce ~]
# cd memcache-2.2.5
[root@soysauce memcache-2.2.5]
# /usr/local/php/bin/phpize
[root@soysauce memcache-2.2.5]
# ./configure --with-php-config=/usr/local/php/bin/php-config --enable-memcache
[root@soysauce memcache-2.2.5]
# make && make install
安装完成,最后一行
Installing shared extensions:
/usr/local/php/lib/php/extensions/no-debug-non-zts-20131226/
为memcache增加配置文件
[root@soysauce memcache-2.2.5]
# vim /etc/php.d/memcache.ini
[root@soysauce memcache-2.2.5]
# cat /etc/php.d/memcache.ini
extension=
"/usr/local/php/lib/php/extensions/no-debug-non-zts-20131226/memcache.so"
重新载入php-fpm服务
[root@soysauce memcache-2.2.5]
# service php-fpm restart
Stopping php-fpm: [ OK ]
Starting php-fpm: [ OK ]
可以看到memcache扩展已经添加完成
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
我们再来用php脚本做下测试
[root@soysauce memcache-2.2.5]
# vim /usr/html/test.php
[root@soysauce memcache-2.2.5]
# cat /usr/html/test.php
<?php
$mem = new Memcache;
$mem->connect(
"127.0.0.1"
, 11211) or die(
"Could not connect"
);
$version = $mem->getVersion();
echo
"Server's version: "
.$version.
"<br/>\n"
;
$mem->
set
(
'testkey'
,
'Hello World'
, 0, 600) or die(
"Failed to save data at the memcached server"
);
echo
"Store data in the cache (data will expire in 600 seconds)<br/>\n"
;
$get_result = $mem->get(
'testkey'
);
echo
"$get_result is from memcached server."
;
?>
|
1
2
3
4
5
6
7
8
9
|
再来使用Telnet登录memcached看一下,可以看到php结合memcached已能正常提供缓存功能
[root@soysauce memcache-2.2.5]
# telnet localhost 11211
Trying 127.0.0.1...
Connected to localhost.localdomain (127.0.0.1).
Escape character is
'^]'
.
get testkey
VALUE testkey 0 11
Hello World
END
|
六、Nginx整合memcached
只需要定义一个server段即可
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
server {
listen 80;
server_name www.soysauce.com;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
set
$memcached_key $uri;
# 以uri为键名
memcached_pass 127.0.0.1:11211;
default_type text
/html
;
error_page 404 @fallback;
}
location @fallback {
proxy_pass http:
//172
.16.1.102;
# 缓存没有时,去哪个主机取得数据
}
}
|
七、保存php session于memcached中
1、配置php将会话保存至memcached中
1
2
3
4
5
6
7
8
9
|
编辑php.ini文件,确保如下两个参数的值分别如下所示
[root@soysauce ~]
# vim /etc/php.ini
session.save_handler = memcache
session.save_path =
"tcp://172.16.1.101:11211?persistent=1&weight=1&timeout=1&retry_interval=15"
重启php-fpm服务
[root@soysauce ~]
# service php-fpm restart
Stopping php-fpm: [ OK ]
Starting php-fpm: [ OK ]
|
2、测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
新建php页面setsess.php,为客户端设置启用session
[root@soysauce ~]
# vim /usr/html/setsess.php
[root@soysauce ~]
# cat /usr/html/setsess.php
<?php
session_start();
if
(!isset($_SESSION[
'www.soysauce.com'
])) {
$_SESSION[
'www.soysauce.com'
] =
time
();
}
print $_SESSION[
'www.soysauce.com'
];
print
"<br><br>"
;
print
"Session ID: "
. session_id();
?>
<?php
session_start();
if
(!isset($_SESSION[
'www.MageEdu.com'
])) {
$_SESSION[
'www.MageEdu.com'
] =
time
();
}
print $_SESSION[
'www.MageEdu.com'
];
print
"<br><br>"
;
print
"Session ID: "
. session_id();
?>
新建php页面showsess.php,获取当前用户的会话ID
[root@soysauce ~]
# vim /usr/html/showsess.php
[root@soysauce ~]
# cat /usr/html/showsess.php
<?php
session_start();
$memcache_obj = new Memcache;
$memcache_obj->connect(
'172.16.1.101'
, 11211);
$mysess=session_id();
var_dump($memcache_obj->get($mysess));
$memcache_obj->close();
?>
用浏览器访问测试
|
八、MemAdmin实现memcached的管理和监控
1、什么是MemAdmin
MemAdmin是一款可视化的Memcached管理与监控工具,使用PHP开发,体积小,操作简单。
主要功能:
-
服务器参数监控:STATS、SETTINGS、ITEMS、SLABS、SIZES实时刷新
-
服务器性能监控:GET、DELETE、INCR、DECR、CAS等常用操作命中率实时监控
-
支持数据遍历,方便对存储内容进行监视
-
支持条件查询,筛选出满足条件的KEY或VALUE
-
数组、JSON等序列化字符反序列显示
-
兼容memcache协议的其他服务,如Tokyo Tyrant (遍历功能除外)
-
支持服务器连接池,多服务器管理切换方便简洁
2、安装与配置
1
2
3
4
5
6
7
8
9
10
11
12
|
首先下载源码包
[root@soysauce ~]
# wget http://www.junopen.com/memadmin/memadmin-1.0.12.tar.gz
解压并移动至网页根目录
[root@soysauce ~]
# tar xf memadmin-1.0.12.tar.gz
[root@soysauce ~]
# mv memadmin /usr/html/memadmin
修改登录密码
[root@soysauce ~]
# vim /usr/html/memadmin/config.php
[root@soysauce ~]
# sed -n "4,5p" /usr/html/memadmin/config.php
$config[
'user'
] =
"admin"
;
//
your username
$config[
'passwd'
] =
"redhat"
;
//
your password
|
3、登录memadmin
添加服务器,我这里memcached服务器是本机
点击左下角的开始管理,即可进入管理页面
这个就是管理页面,支持的操作非常多
这个就是服务器stats统计信息
memadmin还有许多强大的管理功能,这里就不一一去演示了,其实并没有多复杂