为了提高性能,在服务器中采用缓存机制,利用nginx的扩展模块,然后利用nginx的upstream模式可以很方便的给服务器的各种资源加入缓存,大大提高服务器范围的速度。
缓存策略的改进
在传统的缓存系统中,是在代码逻辑中实现的缓存系统,即可能是在php中加入了缓存逻辑。于是,但客户端向服务器发起一个请求时,具体的逻辑会是这样:
client向nginx请求,然后nginx通过fastcgi与后端的php通信,php解析请求,然后往memcache查询业务缓存,最后返回,无论是在哪个环节hold住,都会大大降低系统的性能。
引入nginx-memcached modules后,可以利用nginx的upstream与后端通信,从而绕过后端的其他逻辑处理请求,提升系统的性能。
具体实现
通过加入upstream类似的modules,memcached modules狠方便的可以实现这些功能。前端请求过来后,会先通过uri去查询缓存系统的内容,当缓存系统返回404或是其他500等error里,可以再重新去执行后端的逻辑,具体的逻辑如下:
具体的配置文件如下:
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;
}
}
}
所有评论(0)