Java web开发——使用Oscache来实现页面缓存

        如果想使用Oscache来实现页面缓存,只要导入相应jar包,然后如果想缓存jsp页面内容,需要引入:

 <%@ taglib uri="http://www.opensymphony.com/oscache" prefix="oscache" %>

假如需要缓存当前时间:

现在时间:<%=new Date() %><br>
<oscache:cache time="4">
缓存时间:<%=new Date() %><br>
</oscache:cache>

那么当刷新该页面时第一个时间一直改变,第二个时间每隔4秒才会改变。假如上述页面为默认页面(index.jsp)那么在访问地址

http://localhost:8080/Oscache/index.jsp 

http://localhost:8080/Oscache/

时缓存的时间将会变化,上面2个地址都访问同一个页面,为什么缓存会变化?因为在缓存数据结构中以map,key存储浏览器访问url,上面2个url不一致,缓存肯定变化。此外key也可以自己指定:

现在时间:<%=new Date() %><br>
<oscache:cache time="4" key="mykey">
缓存时间:<%=new Date() %><br>
</oscache:cache>

上面的缓存默认存储在application域当中。当然也可以自己更改,改变缓存到Session:

现在时间:<%=new Date() %><br>
<oscache:cache time="4" scope="session">
缓存时间:<%=new Date() %><br>
</oscache:cache>

缓存也可以存放在文件中,以实现持久化,首先创建oscache.properties(这个配置文件必须在classpath下面):

cache.memory=false
cache.persistence.class=com.opensymphony.oscache.plugins.diskpersistence.DiskPersistenceListener
cache.path=F:\\cache

如果想让Oscache整合web项目(即缓存页面),如,商品页面访问量特别大,给商品页面缓存(Items路径下所有请求都缓存)。可以在web.xml中进行如下配置:

  <filter>
  <filter-name>oscache</filter-name>
  <filter-class>com.opensymphony.oscache.web.filter.CacheFilter</filter-class>
  <init-param>
  <param-name>time</param-name>
  <param-value>3600</param-value>
  </init-param>
  <init-param>
  <param-name>scope</param-name>
  <param-value>application</param-value>
  </init-param>
  </filter>

  <filter-mapping>
  <filter-name>oscache</filter-name>
  <url-pattern>/items/*</url-pattern>
  </filter-mapping>

测试缓存:打一个断点(给商品查询列表),第一次断点必须走,第二次断点不走,走缓存页面。

猜你喜欢

转载自blog.csdn.net/qq_22172133/article/details/81346369