在Java中处理Freemarker语法的最有效方法是什么?

5
这是我们的用例。我们正在从数据库中加载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 方法需要时间,同时执行解析和执行两个步骤?无论如何,你应该进行更详细的分析才能得出结论。 - ddekany
@ddekany,new Template(“TemporaryTemplate”,new StringReader(template),cfg)占用了大部分时间。处理非常快。 - Anil
那么,看起来你将不得不缓存生成的“模板”。如果它确实对你的应用程序太慢了。 - ddekany
@Anil 我也遇到了相同的问题,new Template() 耗费了很长时间。你有找到解决方法吗? - Jestino Sam
1个回答

1
我记得通常不直接调用Template构造函数,而是使用Configuration实例来进行操作(参见获取模板模板加载)。Configuration对象还使用缓存,这可能会有所帮助。您可能需要编写自己的TemplateLoader以从数据库中加载FreeMarker模板。

1
当然,缓存也可以在没有“配置”情况下完成,通过缓存新创建的“模板”。 - ddekany
没错,缓存可以在没有“配置”情况下完成。 - Chaquotay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接