Freemarker是一款非常流行的模板引擎框架,至于基本用法,网上度娘里面有一大堆,我这里就不在叙述了。本文主要介绍的是采用阿里云OSS做未文件服务器,在集群的模式下面,怎么实现静态页面的生成与共享存储。
首先我们知道OSS提供多种文件上传方式:
第一种:文件
第二种:文件流
第三种:byte数组。
我开始的处理方式是:
1、获取模板文件.ftl文件
2、使用模板文件,采用freemarker生成静态页面到本地服务器上的临时文件。
3、读取生成的文件,形成文件流,调用OSS的API上传到阿里云服务器上。
4、删除本地临时文件。
这样的处理方式,流程上是没什么问题,但是会有以下几个弊端:
1、增加IO操作
2、流程复杂化,增加处理时长。
那么现在我们简化流程如下:
1、获取模板文件。
2、采用字符流StringWriter对模板进行处理。
3、通过字符流获取文件内容的字符串。
4、调用OSS的API,将字符串转换成字节数组Put到OSS的服务器上去。
从过程中我们可以很清晰的看出来,我们把中间的文件转换,删除等操作全部去除,从而节省运行成本和IO操作。
最后奉献生成工具类:
public static String createHtml(String modelName, String tempOutPath, Map<String, Object> dataModel,
String reportType,String rootPath,String uploadPath) {
// TODO Auto-generated method stub
StringWriter out = new StringWriter();
try {
// 第一步:创建一个Configuration对象,直接new一个对象。构造方法的参数就是freemarker对于的版本号。
Configuration configuration = new Configuration(Configuration.getVersion());
// 第二步:设置模板文件所在的路径。
configuration.setDirectoryForTemplateLoading(new File(rootPath+File.separator+"WEB-INF"+File.separator+"ftl"));
// 第三步:设置模板文件使用的字符集。一般就是utf-8.
configuration.setDefaultEncoding("utf-8");
// 第四步:加载一个模板,创建一个模板对象。
Template template = configuration.getTemplate(modelName);
// 第六步:创建一个Writer对象,一般创建一FileWriter对象,指定生成的文件名。
// File temFile = new File(uploadPath);
// if(!temFile.exists()){
// temFile.mkdirs();
// }
// File file = new File(uploadPath+tempOutPath+".html");
// if (file.exists()) {
// file.mkdirs();
// }
// Writer out = new FileWriter(file);
// 第七步:调用模板对象的process方法输出文件。
template.process(dataModel, out);
// 第八步:关闭流。
// out.close();
PubAliyunUtil.putObjectToResouceALL(out.toString().getBytes("UTF-8"), "report/"+reportType+"/"+tempOutPath+".html");
//删除文件
// if(file.exists()){
// file.delete();
// }
String url = URL+ "report/"+reportType+"/"+tempOutPath+".html";
QRCodeUtil.encode(url, rootPath+File.separator+"images"+File.separator+"erweima_logo.jpg", true, 2, "report/"+reportType+"/"+tempOutPath+".jpg");
return URL+ "report/"+reportType+"/"+tempOutPath+".jpg";
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}