1. 程式人生 > >nginc+memcache

nginc+memcache

第三方 壓縮包 服務端 客戶端 動態

memcache 分為服務端和客戶端。服務端用來存放緩存,客戶端用來操作緩存。
因此,可以使用 Nginx 直接訪問 Memcache,並用$uri 和$args 等 Nginx 內置變量設定緩存 key規則,這樣,當緩存命中時,Nginx 可以跳過通過 fastcgi 和 PHP 通信的過程,直接從 memcache中獲取數據並返回。
OpenResty是一個基於 Nginx 與 Lua 的高性能 Web 平臺,其內部集成了大量精良的 Lua 庫、第三方模塊以及大多數的依賴項。用於方便地搭建能夠處理超高並發、擴展性極高的動態 Web 應用、Web 服務和動態網關。



1.下載openresty的壓縮包,opwnresty中含有自身的nginx,因此不需要額外安裝nginx

[[email protected] ~]# tar zxf openresty-1.11.2.3.tar.gz
[[email protected] ~]# cd openresty-1.11.2.3
[[email protected] openresty-1.11.2.3]# yum install gcc-c++ -y
[[email protected] openresty-1.11.2.3]# yum install pcre-devel -y
[[email protected] openresty-1.11.2.3]# yum install openssl-devel -y
[[email protected] openresty-1.11.2.3]# ./configure
[[email protected] openresty-1.11.2.3]# gmake
[[email protected] openresty-1.11.2.3]# gmake install
[[email protected] openresty-1.11.2.3]# cd /usr//local/openresty/nginx/conf/



2.更改配置文件
[[email protected] conf]# vim nginx.conf
###########################################
18 http {
19 upstream memcache { ##nginx 模塊中,uosteam 主要用於完成數據的接收,處理,轉發
20 server 127.0.0.1:11211; ##設置默認端口號
21 }
52 location /memc {
53 internal; ##只接受內部訪問,不接收外部 http 請求
54 memc_connect_timeout 100ms;
55 memc_send_timeout 100ms;
56 memc_read_timeout 100ms;
57 set $memc_key $query_string; ##使用 Nginx 內置的$query_string 來作為 key
58 set $memc_exptime 300; ##緩存失效時間
59 memc_pass memcache;
60 } ##將請求的 URL 和後端服務返回的有效結果組成 key-value 存入 memcache服務
72 location ~ \.php$ {
73 set $key $uri$args;
74 srcache_fetch GET /memc $key;
##註冊一個輸入攔截器到 location,這個配置將在location 進入時被執行
75 srcache_store PUT /memc $key;
##註冊一個輸出攔截器到 location,當 location執行完成並輸出時會被執行
76 root html;
77 fastcgi_pass 172.0.0.60:9000;
78 fastcgi_index index.php;
79 include fastcgi.conf;
80 }##為“~ \.php$”配置緩存,表示所有以“.php”結尾的請求都會結果被緩存
}
##當所請求的 uri 以“.php”結尾時,首先到 memcache 中查詢有沒有以$uri$args 為 key 的數據,如果有則直接返回;否則,執行 location 的邏輯,如果返回的 http 狀態碼為 200,則在輸出前以$uri$args 為 key,將輸入結果存入 memcache

###########################################
[[email protected] conf]# /usr/local/openresty/nginx/sbin/nginx -t
[[email protected] conf]# /usr/local/openresty/nginx/sbin/nginx -s reload


[[email protected] conf]# /etc/init.d/httpd start
##註意:http與nginx的端口號都為80,因此需要修改http的端口號
[[email protected] html]# /etc/init.d/iptables stop
[[email protected] html]# yum install memcached -y


測試:
1.開啟memcached,在物理機中進行壓力測試
[[email protected] conf]# /etc/init.d/memcached start
[[email protected] Desktop]# ab -c 10 -n 50000 http://172.25.60.3/index.php
技術分享

2.關閉memcached,在物理機中進行壓力測試
[[email protected] conf]# /etc/init.d/memcached stop
[[email protected] Desktop]# ab -c 10 -n 50000 http://172.25.60.3/index.php
技術分享

nginc+memcache