让以下内容:
<mvc:resources mapping="/resources/**" location="/resources/" />
并说有2000个请求
/resources/script/app/myhax.js
如果我不进行任何配置,是否myhax.js
以某种方式将其缓存到RAM中,其余的请求从那里进行服务,还是全部2000个请求都从文件的真实路径(通常是HDD)得到服务?在直接从内存请求将来服务后,可以将Spring配置为将该文件保留在RAM中吗?
Spring不缓存任何资源。但是有可能为了允许资源被缓存。
您可以指定缓存时间(发送具有给定最大寿命值的缓存头),例如
<resources mapping="/resources/**" location="/resources/" cache-period="3600"/>
或者
mvc:resources
由ResourceHttpRequestHandler支持,因此您可以创建自己的子类来扩展ResourceHttpRequestHandler
和实现缓存逻辑,方法是重写适当的方法,例如writeContent
(注意,可以参考文档或源代码以找到可用方法的列表),并在spring config中使用此新子类。
例如
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class CacheResourceHandler extends ResourceHttpRequestHandler {
private Map<URL, byte[]> cache = new HashMap<>();
@Override
protected void writeContent(HttpServletResponse resp, Resource rsc) throws IOException {
byte[] buff = cache.get(rsc.getURL());
//if not in cache
if (buff == null) {
//add to cache
buff = StreamUtils.copyToByteArray(rsc.getInputStream());
cache.put(rsc.getURL(), buff);
}
//return cache version
StreamUtils.copy(buff, resp.getOutputStream());
}
}
XML配置
我们需要注释掉或删除以前的资源映射
<!--<resources mapping="/resources/**" location="/resources/" />-->
接下来,我们需要声明我们的缓存处理程序bean
<bean id="staticResources" class="CacheResourceHandler">
<property name="locations" value="/resources/"/>
</bean>
最后,我们将使用上面声明的SimpleUrlHandlerMapping来实现HandlerMapping
接口,以便从URL映射到请求处理程序bean。我们需要做的就是传递我们的bean进行映射
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>/resources/**=staticResources</value>
</property>
</bean>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句