1

我们正在使用速度来解析我们的模板。

Velocity 开发人员指南建议为每次解析创建一个新的 VelocityContext

但是VelocityEngineRuntimeInstances呢?

我们可以重复使用它们还是每次调用都创建新实例更好?VelocityEngine 的新实例会导致内存泄漏吗?

  public String parse(String templateStr, Map<String, String> params) {
        StringWriter writer = new StringWriter();
        try {
            VelocityEngine velocityEngine = new VelocityEngine();
            velocityEngine.init();
            RuntimeServices rs = RuntimeSingleton.getRuntimeServices();
            StringReader sr = new StringReader(templateStr);
            SimpleNode sn = rs.parse(sr, "template");

            Template t = new Template();
            t.setRuntimeServices(rs);
            t.setData(sn);
            t.initDocument();

            VelocityContext context = new VelocityContext();

            if (params != null && !params.isEmpty()) {
                for (Entry<String, String> entry : params.entrySet()) {
                    context.put(entry.getKey(), entry.getValue());
                }
            }
            t.merge(context, writer);
        } catch (Exception e) {
            LOGGER.error("Exception in velocity parsing", e);

        }
        return writer.toString();

    }
4

2 回答 2

1

Velocity 允许您使用Singleton 模型

Velocity.setProperty(Velocity.RUNTIME_LOG_NAME, "mylog");
Velocity.init();
Template t = Velocity.getTemplate("foo.vm");

开发人员有两种使用 Velocity 引擎的选项,单例模型和分离实例模型。两种方法都使用相同的核心 Velocity 代码,提供这些代码是为了使 Velocity 更容易集成到您的 Java 应用程序中。

基本上,您可以使用 Velocity 类来代替VelocityEngine

此类提供 Velocity 模板引擎的一个单独的新实例。使用的替代模型是使用采用单例模型的 Velocity 类。

于 2019-09-05T06:13:32.953 回答
0

RuntimeInstance是您不必处理的内部类。

VelocityEngine,以及单例类Velocity(依赖于VelocityEngine),都是可重入的(以及它们关联的模板资源加载器)。这意味着它们可以安全地用于多线程环境。

于 2019-09-05T11:22:50.533 回答