页面静态化主要是把动态生成的HTMl页面变为静态内容进行保存,让后来用户的请求直接访问静态页面,不再经过服务的渲染。
当大量用户访问网站的不同页面,我们需要在后台不断查询数据,再渲染成不同的页面,请求响应时间较长,同时并发能力也较差。如果为了减少服务器压力采用redis缓存,当页面较多的时候也会占用大量的内存,这里我们采用页面静态化主要为了提高并发能力,减少服务器压力。
我们这里使用Thymeleaf实现页面静态化,我们在自己项目service里面建立一个类,代码如下:
@Service
public class GoodsHtmlService {
@Autowired
private TemplateEngine engine;
@Autowired
private GoodsService goodsService;
public void createHtml(Long id){
Context context = new Context();
context.setVariables(this.goodsService.loadData(id));
//把静态文件生成到服务器本地
PrintWriter printWriter = null;
File file = new File("D:\\nginx-1.14.0\\html\\item\\" + id + ".html");
try {
printWriter = new PrintWriter(file);
this.engine.process("item",context,printWriter);
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if (printWriter != null){
printWriter.close();
}
}
}
}
说明一下上述代码中几个重要概念:
- Context:运行上下文
- TemplateEngine:模板引擎
Context
上下文: 用来保存模型数据,当模板引擎渲染时,可以从Context上下文中获取数据用于渲染。
当与SpringBoot结合使用时,我们放入Model的数据就会被处理到Context,作为模板渲染的数据使用。
TemplateEngine
模板引擎:用来解析模板的引擎,需要使用到上下文、模板解析器。分别从两者中获取模板中需要的数据,模板文件。然后利用内置的语法规则解析,从而输出解析后的文件。来看下模板引擎进行处理的函数:
templateEngine.process("模板名", context, printWriter);
生成的静态化页面采用nginx服务器来部署,我们将页面放在nginx的html文件夹中,接着我们在Controller中引用这个方法,返回视图的同时也应该创建一个静态页面,以后访问相同页面就不会请求Controller了,提高了响应速度。
this.goodsHtmlService.createHtml(id);
到这里我们重启项目访问我们的页面,在nginx中就会生成html页面了。最后我们需要在nginx的nginx.conf文件中添加相应配置使它指向本地静态页面,没有找到才进行反向代理。
location /item {
# 先找本地
root html;
if (!-f $request_filename) { #请求的文件不存在,就反向代理
proxy_pass http://127.0.0.1:8084;
break;
}
}