【问题标题】:Is there a way to cache Spring <mvc:resources> files in memory?有没有办法在内存中缓存 Spring <mvc:resources> 文件?
【发布时间】:2014-05-11 21:22:36
【问题描述】:

假设我已将所有 url 绑定到 Spring dispatcher servlet,并在 mvc Sp​​ring 命名空间中使用&lt;mvc:resources&gt; 设置了一些.css.js 目录。

我可以将这些静态 Spring 资源缓存在内存中以避免在用户请求时撞到磁盘吗?

(请注意,我不是在问像 Not Modified 响应这样的 HTTP 缓存,也不是指 Tomcat 静态文件缓存或在 Java 网络服务器前设置另一个网络服务器,只是 Spring 解决方案)

【问题讨论】:

  • cache-period 没有回答你的问题吗?
  • @ArtemBilan 据我所知,它涉及进一步的客户端请求和 HTTP 响应(未修改),但如果新客户端想要下载文件(访问页面),则从磁盘读取。

标签: java spring caching resources static-files


【解决方案1】:

好吧,正如你所说,你想cache你的底层目标资源的全部内容,你必须从inputStream缓存它的byte[]

由于&lt;mvc:resources&gt;ResourceHttpRequestHandler 支持,因此无需停止编写自己的子类并直接使用它来代替自定义标记。

并在覆盖的 writeContent 方法中实现您的缓存逻辑:

public class CacheableResourceHttpRequestHandler extends ResourceHttpRequestHandler {

        private Map<URL, byte[]> cache = new HashMap<URL, byte[]>();

        @Override
        protected void writeContent(HttpServletResponse response, Resource resource) throws IOException {
            byte[] content = this.cache.get(resource.getURL());
            if (content == null) {
                content = StreamUtils.copyToByteArray(resource.getInputStream());
                this.cache.put(resource.getURL(), content);
            }
            StreamUtils.copy(content, response.getOutputStream());
        }

    }

并将它从 spring 配置中用作通用 bean:

<bean id="staticResources" class="com.my.proj.web.CacheableResourceHttpRequestHandler">
    <property name="locations" value="/public-resources/"/>
</bean>

<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="mappings">
        <value>/resources/**=staticResources</value>
    </property>
</bean>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    • 2020-08-27
    • 2022-09-25
    • 2012-03-12
    相关资源
    最近更新 更多