动静分离

动静分离

1.什么是动静分离

动态资源(jsp、ftl、thymeleaf)与静态资源(js、css、img)分开部署。

2.为什么要动静分离

如果我们静态资源与动态资源存放在同一台服务器上面,当静态资源不断增多的时候,我们的服务器访问是扛不住,因为静态资源消耗过多的带宽,导致静态资源无法访问或者访问非常的慢。

image

3.实现动静分离

案例1

在昨天的bbs项目中我们把静态文件单独分离出来

先把web01中的static目录复制出一份挂载到nfs中,然后lb01也创建static文件夹挂载到nfs中,这样lb01中也会出现静态文件

1、创建NFS挂载点
mkdir /static
vim /etc/exports
/static      172.16.1.0/20(rw,sync,all_squash,anonuid=666,anongid=666)
systemctl restart nfs-server
chown -R www.www /static/

# 在lb01中
2、挂载到lb
yum install nfs-utils -y
mount -t nfs 172.16.1.31:/static /opt/static/

# 在web01中
3、将静态资源放置于挂载点内
mkdir /opt/static/s
[root@web01 static]# cp -r /opt/bbs/static/* /opt/static/s/

# 在lb01中
upstream bbs {
    server 172.16.1.7:80 max_fails=3 fail_timeout=3s;
    server 172.16.1.8:80 max_fails=3 fail_timeout=3s;
    server 172.16.1.9:80 max_fails=3 fail_timeout=3s;
}
server {
    listen 80;
    server_name py.test.com;
    location / {
        proxy_pass http://bbs;
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_404;
        include /etc/nginx/proxy_params;
    }
    location ~ \.(jpg|png|css|gif|js|json|woff|woff2)$ {
        root /opt/static;   # 把这个location写入 (\.是转义.)
    }
}

测试

image

案例2

把超级玛丽实现动静分离(因为之前已经把图片挂载到nfs上,所以只需要把lb01挂载上去就行了)

[root@lb01 conf.d]# mkdir images
[root@lb01 conf.d]# mount -t nfs 172.16.1.31:/web/images /opt/images
# 在lb01中
[root@lb01 conf.d]# vim supermary.conf
upstream supermary {
    server 172.16.1.7:80;
    server 172.16.1.8:80;
    server 172.16.1.9:80;
}

server {
    listen 80;
    server_name youxi.com;

    location / {
        proxy_pass http://supermary;
        include /etc/nginx/proxy_params;
    }

    location ~ \.(png|gif)$ {
        root /opt;
    }
}

image

posted @ 2022-01-08 09:33  zong涵  阅读(313)  评论(0编辑  收藏  举报