【问题标题】:What is the most efficient method to process a String Freemarker syntax in Java在Java中处理String Freemarker语法的最有效方法是什么
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 当然,缓存也可以不用Configuration,通过缓存新创建的Template-s。
  • 是的,没有Configuration也可以缓存,你说得对。
猜你喜欢
  • 2010-11-27
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 2014-01-27
  • 1970-01-01
  • 2019-07-02
  • 2019-10-25
相关资源
最近更新 更多