这是我们的用例。我们正在从数据库中加载freemarker语法并进行处理。我们处理了接近一百万条记录。一切都运行良好。但是当我对应用程序进行分析时,我发现我的freemarker处理方法是瓶颈,并且花费了大部分时间。阅读freemarker文档后,我得到了一些指针,了解了我的问题所在。每次进行处理时,我都会创建一个新的freemarker.template.Template对象(其创建似乎很昂贵)。我找不到更正确/更有效的方法来做这件事。
public FTLTemplateEngine() {
cfg = new Configuration();
}
public String process(String template, Map<String, Object> input) throws IOException, TemplateException {
String rc = null;
final Writer out = new StringWriter();
try {
final Template temp =new Template("TemporaryTemplate", new StringReader(template), cfg);
temp.process(input, out);
}
catch (InvalidReferenceException e) {
log.error("Unable to process FTL - " + template);
throw new InvalidReferenceException("FTL expression has evaluated to null or it refers to something that doesn't exist. - " + template, Environment.getCurrentEnvironment());
}
catch (TemplateException e) {
log.error("Unable to process FTL - " + template);
throw new TemplateException("Unable to process FTL - " + template, e, Environment.getCurrentEnvironment());
}
catch (IOException e) {
log.error("Unable to process FTL - " + template);
throw new IOException("Unable to process FTL - " + template);
}
rc = out.toString();
out.close();
return rc.trim();
}
看一下每次需要解析Freemarker的过程方法。在这个方法中,我们每次都创建一个新的Template对象。有没有办法避免这种情况呢?
Template.process
是执行模板的方法,new Template
则是解析模板的方法。或者你是指 你自己的process
方法需要时间,同时执行解析和执行两个步骤?无论如何,你应该进行更详细的分析才能得出结论。 - ddekanynew Template()
耗费了很长时间。你有找到解决方法吗? - Jestino Sam