谷粒商城-高级-46 性能优化-Nginx 动静分离
一、为何动静分离?
可以看到,我们项目的静态资源请求和动态请求都是经过Nginx反向代理后到我们后端的Tomcat服务器,然后再返回数据,如果请求量非常的大,则后端服务器Tomcat的压力也就非常大,经过测试发现,大多数请求都是静态资源的,所以,如果降静态资源放在Nginx下,不用再到Tomcat处理,那就可以大大减轻Tomcat的压力。
二、实施
将我们微服务项目下的静态资源放到Nginx 服务下
// 拷贝本地文件夹到Nginx远程服务器
scp -r /Users/kaiyiwang/Code/gulimall/gulimall-product/src/main/resources/static root@192.168.10.10:/mydata/nginx/html/
登录Nginx服务器,可以看到static文件夹已经上传成功了
[vagrant@localhost html]$ pwd
/mydata/nginx/html
[vagrant@localhost html]$ ls -l
total 0
drwxr-xr-x. 3 root root 19 Aug 31 06:37 static
可以看到已经上传成功了,将我们本地项目下的静态资源删掉。
替换原来模板文件 index.html
静态资源引入的路径:
href="/index/css/swiper-3.4.2.min.css"
// 替换为下边这个
href="/static/index/css/swiper-3.4.2.min.css"
修改Nginx配置文件 gulimall.conf
:
[root@localhost conf.d]# cat gulimall.conf
server {
listen 80;
server_name gulimall.com;
#charset koi8-r;
#access_log /var/log/nginx/log/host.access.log main;
# 如果路径包含static,则直接访问nginx/html的静态路径资源,其余走proxy_pass代理
location /static/ {
root /usr/share/nginx/html;
}
location / {
#proxy_pass http://192.168.10.1:10000;
proxy_set_header Host $host;
proxy_pass http://gulimall; #use nginx.conf upstream load balancing
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 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 http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
然后重启Nginx
docker restart nginx
访问商城gulimall.com:
可以看到我们的商城项目的静态资源已经可以成功地从Nginx访问了。
为者常成,行者常至
自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)