php+memcache和openresty+memcache

来源:互联网 发布:换域名 编辑:程序博客网 时间:2024/04/24 07:55
######php+memcache和openresty+memcache######
client---->nginx---->php-fpm---->php+memcache

memcache是一个高性能的分布师内存对象缓存系统,通过在内存里维护一个巨大的hash表,能够用来存储各种格式的数据。可以类比于mysql这样的服务,而php扩展memcache实际上是是连接memcahe的方式,一般的使用目的是通过缓存数据查询结果,减少终端的访问次数,以提高动态web应用的速度,提高扩展性能。

1.php+memcache

[root@server1 ~]# tar zxf lamp/memcache-2.2.5.tgz

[root@server1 ~]# cd memcache-2.2.5/
[root@server1 memcache-2.2.5]# phpize
##当php编译完成后,php的bin目录下会有phpize这个脚本文件。在编译你要添加的扩展模块之前,执行phpize命令,这里我们在php中加入memcache扩展模块
Configuring for:
PHP Api Version:         20131106
Zend Module Api No:      20131226
Zend Extension Api No:   220131226
[root@server1 memcache-2.2.5]#./configure
[root@server1 memcache-2.2.5]#make
[root@server1 memcache-2.2.5]#make install
Installing shared extensions:     /usr/local/lnmp/php/lib/php/extensions/no-debug-non-zts-20131226/
[root@server1 memcache-2.2.5]# cd /usr/local/lnmp/php/lib/php/extensions/no-debug-non-zts-20131226/
[root@server1 no-debug-non-zts-20131226]# ls
memcache.so  opcache.a  opcache.so
[root@server1 no-debug-non-zts-20131226]# cd /usr/local/lnmp/php/etc/
[root@server1 etc]# ls
pear.conf  php-fpm.conf  php-fpm.conf.default  php.ini
[root@server1 etc]# vim php.ini         ##php-memcache模块扩展
871 extension=memcache.so
[root@server1 etc]# /etc/init.d/php-fpm reload    ##生效
Reload service php-fpm  done
[root@server1 etc]# php -m | grep memcache
memcache
[root@server1 memcache-2.2.5]# yum install memcached.x86_64 -y

[root@server1 memcache-2.2.5]# /etc/init.d/memcached start
Starting memcached:                                        [  OK  ]
[root@server1 memcache-2.2.5]# netstat -antlp | grep :11211    ##memcache监听11211端口
tcp        0      0 0.0.0.0:11211               0.0.0.0:*                   LISTEN      3775/memcached      
tcp        0      0 :::11211                    :::*                        LISTEN      3775/memcached      
[root@server1 memcache-2.2.5]# yum install  telnet -y    ##安装测试命令
Memcached 有 4 种类型的命令:
存储命令(set/add /replace/append/prepend)指示服务器储存一些由键值标识的数据。客户端发送一行命令,后面跟着数据区块;然后,客户端等待接收服务器回传的命令行,指示成功与否
读取命令(get/bget/gets)指示服务器返回与所给键值相符合的数据(一个请求中右一个或多个键值)。客户端发送一行命令,包括所有请求的键值;服务器每找到一项内容,都会发送回客户端一行关于这项内容的信息,紧跟着是对应的数据区块;直到服务器以一行“END”回应命令结束。
状态命令(stat)被用于查询服务器的运行状态和其他内部数据。其他命令,如 flush_all,version,quit 等。
存储命令命令格式:
<command name> <key> <flags> <exptime> <bytes>
<data block>
命令解释:<command name> set/add/replace
    <key> 查找关键字
    <flags> 客户机使用它存储关于键值对的额外信息
    <exptime> 该数据的存活时间,0 为永远
    <bytes> 存储字节数
    <data block> 存储的数据块
[root@server1 memcache-2.2.5]# telnet localhost 11211    
Trying ::1...
Connected to localhost.
Escape character is '^]'.
set name 0 0 6 #第一个0表示   第二个0表示有效期,这里0表示永远 6表示字节数
westos
STORED
get name
VALUE name 0 6
westos
END
set name 0 0 6
haha

STORED
get name
VALUE name 0 6
haha

END
delete name
DELETED
get name
END

quit


[root@server1 memcache-2.2.5]# cp example.php /usr/local/lnmp/nginx/html/
[root@server1 memcache-2.2.5]# cp memcache.php /usr/local/lnmp/nginx/html/
[root@server1 memcache-2.2.5]# vim /usr/local/lnmp/nginx/html/memcache.php
 22 define('ADMIN_USERNAME','admin');       // Admin Username        ##设置用户和密码
 23 define('ADMIN_PASSWORD','westos');      // Admin Password
 24 define('DATE_FORMAT','Y/m/d H:i:s');
 25 define('GRAPH_SIZE',200);
 26 define('MAX_ITEM_DUMP',50);
 27
 28 $MEMCACHE_SERVERS[] = '127.0.0.1:11211'; // add more as an array    ##指定本机的11211端口
 29 //$MEMCACHE_SERVERS[] = 'mymemcache-server2:11211'; // add more as an array
 30

通过刷新网页可以看到命中率的数据更新,几乎接近100%,数据全部来源于缓存



2.openresty+memcache

nginx本身具有高并发的特点,如果将数据缓存放在php后面,则客户请求发给nginx,nginx给php-fpm处理,然后将获取的数据缓存到memcache上,则nginx只有在等待php-fpm处理结束后,必定会影响数据传输速率,如果将memcache直接与nginx连接,当客户发出请求时,nginx直接从memcahce中将数据出给客户端,即可提高速率,这里我们使用openresty来实现。

在php+memcache模块中,即使memcahce命中,还是要进入memcahce生命周期,效率并不高,因此一种更高效的缓存策略是nginx直接访问memcache即使用openresty,并用$uri和$args等nginx内置变量设定缓存key规则,这样当命中缓存时,nginx可以跳过通过fastcgi和php通信过程,直接从memcache中获取数据并返回,提高效率。
[root@server1 lamp]# tar zxf openresty-1.11.2.3.tar.gz
[root@server1 lamp]# cd openresty-1.11.2.3
[root@server1 openresty-1.11.2.3]# nginx -s stop    ##关闭之前的nginx

[root@server1 openresty-1.11.2.3]# ./configure


[root@server1 openresty-1.11.2.3]# gmake && gmake install


[root@server1 openresty-1.11.2.3]# cd /usr/local/openresty/nginx/conf/
[root@server1 conf]# vim nginx.conf (注释写在每段的下方)
 17 http {
 18         upstream memcache {        ##设定负载均衡的服务器列表,可以指定多个服务器。
 19         server 172.25.66.1:11211;
 20         keepalive 512;
 21         }
##keepalive指令是指http-upstream-keeplive-module提供的功能,这里我们最大保持512个立即不关闭的连接用于提高性能
 47         location / {
 48             root   html;
 49             index index.php index.html index.htm;
 60         location /memc {
 61                 internal;
 62                 memc_connect_timeout 100ms;
 63                 memc_send_timeout 100ms;    ##后端服务器数据回传时间
 64                 memc_read_timeout 100ms;    ##连接成功后,后端服务器响应时间
 65                 set $memc_key $query_string;
 66                 set $memc_exptime 300;
 67                 memc_pass memcache;
 68         }
##这里为memc-nginx-module配置location,我们配置为/memc,所有请求都通过这个locaion来操作memcache,memc-nginx-module存取    memcache是基于http method语义的,使http的GET方法表示get,PUT方法表示set,DELETE方法表示delete。internal表示只接受内部网络,不接受外部http请求,如果需要接受外部访问 ,可以使用allow和deny来指令控制权限。$memc_key表示以什么key,这里直接使用nginx内置的$query_string来作为key,$memc_exptime表示缓存失效时间,以秒记,实际应用中根据具体情况设置。
 77         location ~ \.php$ {        ##设置url以.php结尾
 78             set $key $uri$args;
 79             srcache_fetch GET /memc $key;
 80             srcache_store PUT /memc $key;
 81             root           html;
 82             fastcgi_pass   127.0.0.1:9000;
 83             fastcgi_index  index.php;
 84             #fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
 85             include        fastcgi.conf;
 86         }
##~ \.php$这个location配置了缓存,这表示所有以.php结尾的请求结果都会被缓存。srcache_fetch表示注册一个输入拦截处理器到location,这个配置进入时将被执行;而srcache_store表示注册一个输出拦截器到location,当location执行完成输出时会被执行。

完成以上配置后,相当于对nginx增加了这些逻辑:当所有请求以"'.php"结尾时,首先到memcahce中查询有没有以$url$args为key的数据,如果有则返回,否则执行location的逻辑。


[root@server1 conf]# nginx -t
nginx: the configuration file /usr/local/lnmp/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/lnmp/nginx/conf/nginx.conf test is successful
[root@server1 conf]# nginx -s reload


测试:
[kiosk@foundation6 Desktop]$ ab -c10 -n 50000 http://172.25.66.1/index.php
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 172.25.66.1 (be patient)
Completed 5000 requests
Completed 10000 requests
Completed 15000 requests
Completed 20000 requests
Completed 25000 requests
Completed 30000 requests
Completed 35000 requests
Completed 40000 requests
Completed 45000 requests
Completed 50000 requests
Finished 50000 requests


Server Software:        nginx/1.10.1
Server Hostname:        172.25.66.1
Server Port:            80

Document Path:          /index.php
Document Length:        169 bytes

Concurrency Level:      10
Time taken for tests:   5.265 seconds
Complete requests:      50000
Failed requests:        0
Write errors:           0
Non-2xx responses:      50000
Total transferred:      15950000 bytes
HTML transferred:       8450000 bytes
Requests per second:    9496.84 [#/sec] (mean)
Time per request:       1.053 [ms] (mean)
Time per request:       0.105 [ms] (mean, across all concurrent requests)
Transfer rate:          2958.49 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.1      0       3
Processing:     0    1   0.2      1       4
Waiting:        0    1   0.2      1       4
Total:          0    1   0.2      1       4

Percentage of the requests served within a certain time (ms)
  50%      1
  66%      1
  75%      1
  80%      1
  90%      1
  95%      1
  98%      1
  99%      2
 100%      4 (longest request)