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

Ani*_*nil 5 java freemarker

这是我们的用例。我们正在从数据库加载 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();
    }   
Run Code Online (Sandbox Code Playgroud)

查看每次需要解析 Freemarker 时调用的 process 方法。在这个方法中,我们每次都创建新的 Template 对象。有没有办法避免这种情况?

Cha*_*tay 1

AFAIR 通常不会Template直接调用构造函数,而是使用Configuration实例来执行此操作(请参阅获取模板模板加载)。该Configuration对象还使用了缓存,这可能会有所帮助。您可能需要编写自己的模板TemplateLoader才能从数据库加载 FreeMarker 模板。