springboot+thymeleaf+nginx實現頁面靜態化

適用場景

  • 在高併發的情況下,為了緩解服務器動態解析的壓力,利用nginx處理靜態文件的優點,可將系統中修改次數較少的頁面進行靜態化處理。

自定義工具類

<code>import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
public class ThymelafUtils {
/**
* 生成頁面的方法
* @param variables 傳入參數
* @param dirPath 文件目錄地址
* @param filePath 文件地址路徑
* @param templatePage 模板頁面
* @param templateEngine 模板引擎
*/
public static void createHtmlPage(HashMap variables, String dirPath, String filePath, String templatePage,TemplateEngine templateEngine){

// 創建上下文,
Context context = new Context();
// 把數據加入上下文
context.setVariables(variables);
if (!new File(dirPath).exists()){
new File(dirPath).mkdirs();
}
// 創建輸出流,關聯到一個臨時文件
File temp = new File(filePath);
try (PrintWriter writer = new PrintWriter(temp, "UTF-8")) {
// 利用thymeleaf模板引擎生成 靜態頁面
templateEngine.process(templatePage, context, writer);
} catch (IOException e) {
System.out.println("頁面靜態化出錯:{}"+e.getMessage());
}
}
}/<code>

nginx環境配置

<code>server {
listen 80;
server_name location;
\t\t#區分大小寫匹配.html結尾的請求
\t\tlocation ~ \\.html{
\t\t\troot html; #本人將靜態化的頁面放入nginx的html目錄下,可根據需求自行修改
\t\t\tif (!-f $request_filename) { #請求的文件不存在,就反向代理
\t\t\t\tproxy_pass http://127.0.0.1:8092; #地址路徑為要生成頁面的請求路徑(自行修改)
\t\t\t\tbreak;
\t\t\t}
\t\t}
\t}/<code>

配置文件(application.properties)

<code>#為nginx安裝目錄中html下
htmlPath=E:/nginx/nginx-1.16.0/nginx-1.16.0/html/ /<code>

調用方法

<code>
@Autowired
private TemplateEngine templateEngine;//模板引擎

@Value("${htmlPath}")
String htmlPath; //生成文件路徑的地址

@RequestMapping(value = "/{skuId}.html",method = RequestMethod.GET)
public String getItemInfo(@PathVariable("skuId") String skuId, Model model){

//配置傳入參數
HashMap<string> variables=new HashMap();
//自行根據業務需求將數據以kv鍵值對的形式將參數進行傳入
//variables.put("skuInfo",skuInfo);

//設置路徑
String filePath=htmlPath+skuId+".html";


//生成頁面的模板頁面地址
String templatePage="item";

//本人自己新增靜態化頁面的功能
ThymelafUtils.createHtmlPage(variables,htmlPath,filePath,templatePage,templateEngine);

return "redirect:"+skuId+".html"; //將服務重定向,若存在靜態頁面,就直接有nginx轉發
}/<string>/<code>

實現思路

  • 利用thymeleaf模板引擎進行頁面靜態化,將生成的頁面放入nginx安裝目錄的html文件夾下。頁面生成後請求重定向給nginx進行轉發。
  • 用戶訪問時,先有nginx判斷是否有該頁面,若無,則將請求發送給controller層進行頁面的創建。


分享到:


相關文章: