繁体   English   中英

Apache Velocity禁用模板和资源缓存

[英]Apache Velocity disable template & resource caching

我有一个Spring Boot应用程序,该应用程序公开了一个用于渲染相对简单的速度模板的API。 该模板使用#parse来包含其他两个模板,否则会写出从Java层传递给它的一些基本变量。 模板位于JAR文件中,因此它们是从类路径加载的。 我使用以下根据每个请求即时创建的速度引擎设置:

    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    ve.setProperty("classpath.resource.loader.cache", "false");
    ve.setProperty("velocity.engine.resource.manager.cache.enabled", "false");
    ve.setProperty("resource.manager.cache.enabled", "false");
    ve.init();

模板的多个部分意味着每个请求都是唯一的(该资源用作对简单Spring MVC控制器的响应),因此我需要禁用模板资源的缓存。 我已经按原样尝试了上述配置,并且在src/main/resources中的velocity.properties文件中对其进行了定义,但是更改模板或文件直到重新启动应用程序后才“生效”。

按照本文档页面的说明进行操作似乎无济于事(实际上,您可以在上面看到它的作用)。

上面的引擎代码在Spring Component类内部,即使每次将VelocityEngine内容移动到静态的final字段并每次都只初始化速度上下文时也没有帮助。

如何强制Spring / Velocity每次加载模板和包含的资源?

您只需要classpath.resource.loader.cache配置键。 而且由于Velocity中的所有缓存默认都为false,因此您甚至不需要它。

同样,无需在每次请求时重新初始化VelocityEngine。

我用以下小测试程序检查了修改后正确重新加载的资源:

import java.io.PrintWriter;
import java.io.Writer;
import java.util.Scanner;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;    

public class Test
{
    public static void main(String args[])
    {
        try
        {
            VelocityEngine ve = new VelocityEngine();
            ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
            ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
            // next line not needed since 'false' is the default
            // ve.setProperty("classpath.resource.loader.cache", "false");
            ve.init();

            VelocityContext context = new VelocityContext();
            Writer writer = new PrintWriter(System.out);
            Scanner scan = new Scanner(System.in);
            while (true)
            {
                System.out.print("> ");
                String str = scan.next();
                context.put("foo", str);
                ve.mergeTemplate("test.vm", "UTF-8", context, writer);
                writer.flush();
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

如果它在您的情况下不起作用, 特别是如果您在每个请求中重新初始化Velocity,那么在Spring本身中肯定是ClassLoader缓存问题。

因此,您应该查看Spring Hot Swapping指南,以了解如何禁用缓存。 我想对Spring有更深入了解的人可以为您提供在这种特殊情况下如何进行操作的提示。

令人尴尬的是,一旦更改模板或资源(例如使用Ctrl + F9),我就需要通过IntelliJ进行编译。 不过,感谢@Claude Brisson的帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM