由于nginx的标准Memcached模块HttpMemcachedModule没有完全实现Memcached协议,只能读取Memcached而不能写入,所以目前流行的cache方案如下图所示:
Nginx读取Memcached,如果失败,那么把请求转发给后台的服务器,并返回结果,后台服务器处理结束后,还需要把结果写入Memcached,这样下次请求到Nginx时就可以直接从Memcached读取数据了。
延伸阅读:memcachedb的编译与安装
一、安装
1、安装Libevent
复制代码 代码示例:
#
yum install libevent libevent-devel
2、安装Memcached
下载Memcached,执行如下命令安装Memcached:
复制代码 代码示例:
#tar -zxvf memcached-1.4.15.tar.gz
#cd memcached-1.4.15
#./configure
#make
#make install
Memcached默认安装到/usr/local/bin下,执行如下命令可以启动Memcached:
复制代码 代码示例:
#/usr/local/bin/memcached -p 11211 -m 64m -d
上面命令用daemon后台启动Memcached,监听11211端口,最大内存使用量为64M.
3、安装Nginx
Nginx安装方法,请参考文章:
注意,在编译前要先安装ngx_http_memcached_module并在configure时加入ngx_http_memcached_module:
复制代码 代码示例:
#./configure --add-module=../HttpMemcachedModule
二、配置
#vi /etc/nginx/nginx.conf
复制代码 代码示例:
user usr usr;
worker_processes 2;
#
http {
types {
text/
javascript js;
application/xml xml;
}
#
# By default, return content sa
default_type application/xml;
#
access_log /home/api/logs/nginx.log main;
#
sendfile on;
tcp_nopush on;
#
keepalive_timeout 65;
tcp_nodelay on;
#
# app. server(s) / cluster definition
upstream dynamic_srv { server 127.0.0.1:9020; }
#
server {
listen 9000;
server_name srv;
root /home/usr;
#
# Match any request that begins with /dynamic_request
location /dynamic_request {
#
# Append a file-extension to every request
if ($args ~* format=json) { rewrite ^/dynamic_request/?(.*)$ /dynamic_request.js$1
break; }
if ($args ~* format=xml) { rewrite ^/dynamic_request/?(.*)$ /dynamic_request.xml$1 break; }
#
# Check if local memcached server can answer this request
memcached_pass 127.0.0.1:11211;
#
# Send to app. server if Memcached could not ansewr the request
error_page 404 = @dynamic_request;
}
#
location @dynamic_feed_id {
# only internal requests can reach this endpoint internal;
#
# dispatch to our app_server cluster / instance
proxy_pass http://dynamic_srv;
}
#
}
}
当然还可以使用淘宝前工程师章亦春共享的NginxHttpMemcModule和srcache-nginx-module来实现Nginx写入Memcached,具体如何使用暂且不表,可以参考:
http://blog.slogra.com/post-180.html
http://blog.codinglabs.org/articles/nginx-memc-and-srcache.html