2014-04-01 31 views
1

假设我已将所有网址绑定到Spring调度程序servlet,并在mvc Sp​​ring命名空间中设置了一些.css.js目录,其中<mvc:resources>有没有办法在内存中缓存Spring <mvc:resources>文件?

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

(请注意,我不是问HTTP缓存像Not Modified响应,也并不意味着Tomcat的静态文件缓存或在Java中webserwer,只是春天的解决方案前建立另一个网站服务器)

+0

不'缓存period'回答你的问题? –

+0

@ArtemBilan据我所知,它涉及进一步的客户端请求和HTTP响应(未修改),但是如果新客户端需要下载文件(访问页面),则会发生磁盘读取。 –

回答

4

嗯,你说你想要cache你的底层目标资源的全部内容,你必须从inputStream缓存它的byte[]

由于<mvc:resources>得到ResourceHttpRequestHandler的支持,所以没有停止来编写自己的子类并直接使用它来代替自定义标记。

而仅有不到overrided 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 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> 
相关问题