路人战队|阿里P7资深架构师Tomcat笔记分享( 二 )


大家可以看到 , 我们网站上有很多的图片 , 每次访问都要去后端的tomcat服务器上去取 , 很消耗服务器资源 。 我们下面将设置在nginx服务器上缓存图片 。
3.Nginx将图片缓存到本地修改配置文件 , 首先修改 /etc/nginx/nginx.conf , 添加缓存的配置:
[root@lamp1 nginx]# cat nginx.confusernginx;worker_processes1;error_log/var/log/nginx/error.log warn;pid/var/run/nginx.pid;events {worker_connections1024;}http {include/etc/nginx/mime.types;default_typeapplication/octet-stream;log_formatmain'$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for"';access_log/var/log/nginx/access.logmain;sendfileon;#tcp_nopushon;keepalive_timeout65;#gzipon;proxy_cache_path /nginx/cache levels=1:2 keys_zone=first:10m inactive=24h max_size=1G; # 设置缓存upstream backend { # 后端 tomcat 服务器server 192.168.0.181:8080 weight=1;}include /etc/nginx/conf.d/*.conf;}接着修改 /etc/nginx/conf.d/default.conf:
[root@lamp1 nginx]# cat conf.d/default.confserver {listen80;server_namelocalhost;#charset koi8-r;#access_log/var/log/nginx/log/host.access.logmain;location / {#root/data/www;#indexindex.php index.html index.htm;proxy_pass http://backend; #}location ~* "\.(jpg|jpeg|png|gif|html|css|js)$" { # 不区分大小写匹配 , 缓存静态文件proxy_pass http://backend;proxy_cache first;proxy_cache_valid 200 24h; # 200 响应缓存 24hproxy_cache_valid 302 10m; # 302 响应缓存 10madd_header X-Cache-Status $upstream_cache_status; # 添加响应首部 , 返回缓存命中信息}#error_page404/404.html;# redirect server error pages to the static page /50x.html#error_page500 502 503 504/50x.html;location = /50x.html {root/usr/share/nginx/html;}# proxy the PHP scripts to Apache listening on 127.0.0.1:80##location ~ \.php$ {#proxy_pass;#}# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000##location ~ \.php$ {#root/data/www;#fastcgi_pass192.168.0.171:9000;#fastcgi_indexindex.php;#includefastcgi_params;#}# deny access to .htaccess files, if Apache's document root# concurs with nginx's one##location ~ /\.ht {#denyall;#}}建立 /nginx/cache 目录 , 然后测试配置语法 , 重新加载配置:
[root@lamp1 nginx]# mkdir -p /nginx/cache[root@lamp1 nginx]# nginx -tnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful[root@lamp1 nginx]# nginx -s reload访问 nginx 服务器地址 , 即可看到 tomcat 首页 , 刷新几次 , 看静态文件被缓存:
路人战队|阿里P7资深架构师Tomcat笔记分享Snip20160811_55.png
路人战队|阿里P7资深架构师Tomcat笔记分享Snip20160811_56.png
以上分别是一个 png 文件和一个 css 文件 , 都显示缓存命中 。 在tomcat 服务器的日志中可看到 , 除了第一次访问 , 后续刷新网页 , 都只发送了一个对根目录的 / 的 HTTP 请求 , 因为首页中除了对 / 的请求 , 其他都是静态文件请求:


推荐阅读