什么是动静分离
- 简单说就是将用户请求的内容中的动态请求和静态请求分开处理
为什么要使用动静分离技术
- 首先tomcat在处理静态资源时效率并不高,需要进行复杂的逻辑运算,导致应用响应变慢,造成不必要的资源侵占
- 借助nginx实现动静分离以后,可以减少系统不必要的消耗和延时,加速处理的性能
【实验】单机实现动静分离
- 安装tomcat、部署代码包
[root@nginx ~]# ls
anaconda-ks.cfg apache-tomcat-9.0.59.tar.gz
[root@nginx ~]# yum -y install java
[root@nginx ~]# mkdir /app
[root@nginx ~]# tar xf apache-tomcat-9.0.59.tar.gz -C /app/
[root@nginx ~]# ln -s /app/apache-tomcat-9.0.59/ /app/tomcat
[root@nginx ~]# /app/tomcat/bin/startup.sh
Using CATALINA_BASE: /app/tomcat
Using CATALINA_HOME: /app/tomcat
Using CATALINA_TMPDIR: /app/tomcat/temp
Using JRE_HOME: /usr
Using CLASSPATH: /app/tomcat/bin/bootstrap.jar:/app/tomcat/bin/tomcat-juli.jar
Using CATALINA_OPTS:
Tomcat started.
- 安装nginx
cat > /etc/yum.repos.d/nginx.repo << OK
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/\$releasever/\$basearch/
gpgcheck=0
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
OK
[root@nginx ~]# yum -y install nginx
[root@nginx ~]# systemctl start nginx
[root@nginx ~]# systemctl enabled nginx
nginx配置动态和静态资源分离处理
[root@nginx code]# groupadd -g666 www
[root@nginx code]# useradd -u666 -g666 www
[root@nginx code]# sed -i '/^user/c user www;' /etc/nginx/nginx.conf
[root@nginx code]# vim /etc/nginx/conf.d/test.conf
server {
listen 80;
server_name www.test.org;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location ~* \.(png|jpg)$ {
root /code/images;
}
}
- 创建图片目录,由于tomcat的网页中的静态资源配置成nginx处理
- 创建的图片目录,权限跟nginx为www
[root@nginx code]# mkdir -p /code/images
[root@nginx code]# cp /app/tomcat/webapps/ROOT/*.png /code/images/
[root@nginx code]# chown -R www.www /code/images/
浏览器测试,页面中的图标、图片是否加载