基於前後端分離的Nginx+Tomcat動靜分離
1.什麽是動靜分離
“動”與“靜”
在弄清動靜分離之前,我們要先明白什麽是動,什麽是靜。
在Web開發中,通常來說,動態資源其實就是指那些後臺資源,而靜態資源就是指Html、img、js、css等文件。
動靜分離就是將動態資源和靜態資源分開,將靜態資源部署在Nginx上,當一個請求來的時候,如果是靜態資源的請求,就直接到nginx配置的靜態資源目錄下面獲取資源,如果是動態資源的請求,nginx利用反向代理的原理,把請求轉發給後臺應用去處理,從而實現動靜分離。
好處
tomcat的優勢在於少量的接收並處理復雜的http請求(將用戶請求讀寫數據庫等),nginx的優勢在於能夠大量的接收並處理簡單的http請求(將http請求轉發或者加個header、body等)。
將Html、img、js、css等這種靜態資源交給nginx,將用戶需要讀寫數據庫等請求交給tomcat是對各自優勢的最大利用。
詳解
Nginx與tomcat各自的優勢與區別詳解參考:tomcat 與 nginx,apache的區別是什麽?.
2.環境準備
需要nginx、tomcat、SpringBoot
2.1 linux
linux環境下的nginx下載、安裝、使用
linux環境下的jdk8下載、安裝、使用
linux環境下的tomcat下載、安裝、使用
2.2 windows
windows環境下nginx下載解壓後,即可使用。
Windows下Nginx的啟動、停止等命令
由於使用SpringBoot,所以使用內嵌的tomcat。
3.正式部署
3.1 前臺
前臺使用一個ajax請求後端,新建一個index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>前後端分離</title> <script type="text/javascript" src="https://cdn.bootcss.com/jquery/1.11.2/jquery.js"></script> <script type="text/javascript"> $(function(){ $("#loginBtn").click(function(){ $.post( "http://localhost:8080/username", function(rtn){ $("#name").text(rtn.username) }); }); }); </script> </head> <body> <form> <input type="button" value="查看當前用戶" id="loginBtn"> <div id="name" style="color:#00FF00"> </div> </form> </body> </html>
將index.html放到nginx的html目錄下(將nginx/html目錄下的文件都刪了)。
正式部署時,只需要將靜態資源扔到html目錄下即可
3.2 後臺
後臺使用SpringBoot,只需一個接收請求的controller即可,這裏為了省事,直接在Application裏面寫controller了。
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@RequestMapping(value = "/username", method = {RequestMethod.GET, RequestMethod.POST})
public User username() {
// 假裝請求了數據庫
User user = new User("tom");
return user;
}
class User {
private String username;
public User(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
}
啟動SpringBoot項目可以訪問到
正式部署時,只需要將SpringBoot打的jar包扔到服務器上啟動即可
//打jar
mvn clean package -Dmaven.test.skip=true
//啟動jar
nohup java -jar ROOT.jar &
3.3 nginx.conf
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
#監聽8080端口,代理前端請求
listen 80;
server_name localhost;
location / {
# 默認訪問html下的index.html
index index.html;
}
}
server {
#監聽8080端口,代理後端請求
listen 8080;
server_name localhost;
location / {
proxy_pass http://localhost:8080;
proxy_set_header X-Real-IP $remote_addr;
}
}
}
啟動nginx
start nginx
nginx.conf的更多配置
Nginx反向代理、負載均衡、動靜分離、緩存、壓縮、防盜鏈、跨域訪問
nginx.conf詳細配置
3.4前後端分離導致動靜分離的跨域問題
訪問http://localhost/
Access to XMLHttpRequest at 'http://localhost:8080/username' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
由於前後端分離了,所以前端http://localhost/使用ajax請求http://localhost:8080/發生了跨域問題。
詳解:
CORS解決跨域問題
Jsonp解決跨域問題
這裏直接給出解決方案,使用CORS解決跨域問題
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
//1.添加CORS配置信息
CorsConfiguration config = new CorsConfiguration();
//1) 允許的域,不要寫*,否則cookie就無法使用了
config.addAllowedOrigin("http://localhost");
//2) 是否發送Cookie信息
config.setAllowCredentials(true);
//3) 允許的請求方式
config.addAllowedMethod("GET");
config.addAllowedMethod("POST");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("PUT");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
// 4)允許的頭信息
config.addAllowedHeader("*");
//2.添加映射路徑,我們攔截一切請求
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
//3.返回新的CorsFilter.
return new CorsFilter(configSource);
}
}
放到Application.java同目錄及以下即可
結構:
重啟項目,再次訪問http://localhost/,訪問成功。
4.總結
總的來說就是將靜態資源html、js、css等放入nginx中,將動態請求交給tomcat。
如果發生跨域,需要在解決跨域問題。
基於前後端分離的Nginx+Tomcat動靜分離