【发布时间】:2015-02-14 11:12:17
【问题描述】:
这是我们的用例。我们正在从数据库中加载 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需要解析时调用的process方法。在这个方法中,我们每次都在创建新的 Template 对象。有没有办法避免这种情况?
【问题讨论】:
-
Template.process执行模板,new Template执行解析。或者你的意思是你的过程方法需要时间,两者都需要?无论如何,你应该做一些更详细的分析来说明这一点。 -
@ddekany, new Template("TemporaryTemplate", new StringReader(template), cfg) 花费了大部分时间。处理速度非常快。
-
那么,看来您将不得不缓存生成的
Template-s。如果它确实对您的应用程序来说太慢了,那就是。 -
@Anil 我也面临同样的问题,
new Template()需要时间。您是否设法找到任何解决方法?
标签: java freemarker