【问题标题】:How to reload templates without reloading server?如何在不重新加载服务器的情况下重新加载模板?
【发布时间】:2016-02-27 05:43:53
【问题描述】:

我正在开发 Java/Spark 框架中的应用程序,并且正在使用 Apache Velocity 模板引擎。我的问题是,每次我更改模板中的任何内容时,我都必须重新加载整个服务器。有没有办法让某种热交换能够在模板上工作而无需重新加载整个服务器?

private final VelocityEngine velocityEngine;

public VelocityTemplateEngine() {
    Properties properties = new Properties();
    properties.setProperty("resource.loader", "class");
    properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    properties.setProperty("class.resource.loader.cache", "true");
    properties.setProperty("class.resource.loader.modificationCheckInterval", "2");
    properties.setProperty("velocimacro.library.autoreload", "true");
    properties.setProperty("velocimacro.permissions.allow.inline.to.replace.global", "true");
    velocityEngine = new org.apache.velocity.app.VelocityEngine(properties);
    //velocityEngine.init(); <-- This bit of code does not change anything when uncommented...
}

解决方案:
通过将 resource.loader 更改为 file 并将 class.resource.loader.class 更改为 org.apache.velocity.runtime 来解决。 resource.loader.FileResourceLoader

properties.setProperty("resource.loader", "file");
properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");

properties.setProperty("file.resource.loader.path", root + "/src/main/resources/"); // "root" points to the app folder

properties.setProperty("class.resource.loader.cache", "true"); // Enable cache
properties.setProperty("class.resource.loader.modificationCheckInterval", "2"); // Check for new files every 2 seconds

【问题讨论】:

  • 感谢 Jaboc 的解决方案!现在我可以使用缓存的性能优化,无需重启服务器即可上传.vms

标签: java velocity spark-framework


【解决方案1】:

试试这个:

  1. 初始化速度引擎实例。 VelocityEngine x = new VelocityEngine();
  2. 设置属性:

     file.resource.loader.class= FileResourceLoader classname
     file.resource.loader.path=  template location
     file.resource.loader.cache= true
     file.resource.loader.modificationCheckInterval= duration in which you want to reload the templates
    
  3. x.int();

这里的重要一点是,您不会在每次请求时再次初始化速度引擎。在创建速度引擎对象时做这样的事情:

  VelocityEngine x;   // instance variable

  if(x==null)
  {
   x = new VelocityEngine();
   x.init();
   }
  else
  {
   x;
   }

【讨论】:

  • 我以前试过这个,但没有任何成功。
  • 对我来说,这种模式效果很好。您的代码中可能存在一些小缺陷。能不能说的详细一点。
  • 您正在使用类路径资源加载器。尝试使用 FileResource 加载器。
  • 你能给我举个例子吗?我是 Velocity 的菜鸟。
  • 这里有一些例子:programcreek.com/java-api-examples/…
猜你喜欢
  • 1970-01-01
  • 2012-10-03
  • 2011-07-21
  • 1970-01-01
  • 1970-01-01
  • 2011-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多