freemark静态化页面
学习点:
1.为什么需要使用freemark
2.怎么使用freemark
前言
为什么使用freemark?
热点数据的详情页访问频率非常高,详情页的数据加载,我们可以采用直接从数据库查询加载,但这种方式会给数据库带来极大的压力,甚至崩溃,这种方式我们并不推荐。
针对存在像有详情页存在的数据展现,例如商品或者像文章数据,数据介绍、数据标题、数据图片、数据数量等,大部分数据几乎不变,可能只有数量会变,因此我们可以考虑把数据详情页做成静态页,例如商品,每次访问只需要加载库存数量[这个库存也可以存储在Redis做原子递减,最终一致性同步到数据库,还可以避免超卖],这样就可以大大降低数据库的压力。
一、如何使用freemark
导入pom文件
<!--freemarker-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
在yml文件中配置
#freemarker配置
freemarker:
cache: false #关闭模板缓存,方便测试
settings:
template_update_delay: 0 #检查模板更新延迟时间,设置为0表示立即检查,如果时间大于0会有缓存不方便进行模板测试
template-loader-path: classpath:/templates
charset: UTF-8
check-template-location: true
suffix: .ftl
content-type: text/html
expose-request-attributes: true
expose-session-attributes: true
request-context-attribute: request
# 静态页生成的位置 注意修改为自己指定的路径
htmlPath: C:/5_code/html
定下程序中生成freemark模板的接口
/**
* 生成静态页
*/
void writePage(Map<String,Object> dataMap) throws Exception;
实现生成freemark模板的接口
@Autowired
private Configuration configuration;
/**
* 生成静态页
*
* @param dataMap dataMap.templateName: 模板名字,例如item.ftl,模板放到resources/templates目录下
* dataMap.path: 生成文件存储路径,例如C:/page/html
* dataMap.name: 生成的文件名字,例如:12345.html
*/
@Override
public void writePage(Map<String, Object> dataMap) throws Exception {
//获取模板名字
String templateName = dataMap.get("templateName").toString();
//文件生存的路径
String path = dataMap.get("path").toString();
//文件路径如果不存在,则创建
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
//获取文件名字
String fileName = dataMap.get("name").toString();
//获取模板对象
Template template = configuration.getTemplate(templateName);
//模板处理,获取生成的文件字符串
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, dataMap);
//生成文件
FileUtils.writeStringToFile(new File(path, fileName), content);
}
数据的解释
templateName:模板名字,例如item.ftl,模板放到templates目录下
path:生成文件的路径,例如C:/page/html
name:生成静态页文件的名字,例如:item.html
具体使用
@Value("${htmlPath}")
private String htmlPath;
@Autowired
private SkuPageService skuPageService;
/**
* 测试详情静态页
*/
@PostMapping(value = "/html")
public Result html() throws Exception {
String id = "1234";
//数据模型
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("templateName", "test.ftl"); //模板名字
dataMap.put("name", id + ".html"); //生成静态页的文件名字
dataMap.put("path", htmlPath); //生成的静态页路径
dataMap.put("title", "笔记本电脑"); //数据
dataMap.put("arr", new String[]{"1", "2", "3"}); //集合
//生成静态页
skuPageService.writePage(dataMap);
return new Result(true, StatusCode.OK, "生成成功!");
}
freemark使用到的页面
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>静态页测试</title>
</head>
<body>
<h3>${title}</h3>
<#list arr! as a>
${a}<br/>
</#list>
</body>
</html>
总结
关于对freemark的技术的,为什么要使用,以及如何使用的总结。