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层进行页面的创建。


分享到:


相關文章: