您的位置:首页 > 编程语言 > Java开发

Spring基于注解ehCache缓存整合

2017-12-12 10:00 603 查看
注解的使用参照:http://blog.csdn.net/wjacketcn/article/details/50945887 (侵删)

ehCache是纯java实现的缓存组件,spring从3.1开始引入了对ehcache的支持。

使用:

  1、在pom.xml中添加依赖

     <dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.9.1</version>
</dependency>


  2、在classPath下增加ehcache配置文件ehcache.xml

  <?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false">
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
       <!--这个名称会用到-->
<cache name="myCache"      
maxElementsInMemory="10000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="30"
timeToLiveSeconds="60"
memoryStoreEvictionPolicy="LFU"
/>
</ehcache>


  3、applicationContext.xml 添加配置(类似于事物配置)

     <!--开启缓存的注解功能,否则注解无法生效-->
<cache:annotation-driven />
<!-- 声明缓存管理器 -->
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehCacheFactory"></property>
</bean>
<!--指定工厂类及ehcache.xml文件位置-->
<bean id="ehCacheFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml"/>
</bean>


  4、在service层添加注解

     @Cacheable(value="myCache")  //这个名称就是ehcache.xml文件中的name属性的值
public List<FreeUrl> findAll(){
return freeUrlMapper.findAll();
}


案例:拦截器放过免认证的路径

  创建表:freeUrl 

      CREATE TABLE `freeurl` (

        `id` int(11) NOT NULL,

        `url` varchar(255) DEFAULT NULL,

        PRIMARY KEY (`id`)

      )

  上述配置完成之后进行如下配置

  1、在spring-mvc.xml中配置拦截器路径  

     <mvc:interceptors>
<bean class="com.util.interceptors.LoginInterceptors"/>
</mvc:interceptors>


  2、编写service代码并将查询结果存入缓存

     @Cacheable(value="myCache")
public List<FreeUrl> findAll(){
return freeUrlMapper.findAll();
}


  3、编写拦截器代码

    public class LoginInterceptors extends HandlerInterceptorAdapter{
private Logger log = LogManager.getLogger(LoginInterceptors.class);
@Resource
private FreeUrlService freeUrlService;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
//获取项目路径
String contextPath = request.getContextPath();
//获取访问路径
String requestPath = request.getServletPath();

HttpSession session = request.getSession();

//查询免认证路径
List<FreeUrl> list = freeUrlService.findAll();
for (FreeUrl freeUrl : list) {
//如果请求路径为免认证路径则放开
if(freeUrl.getUrl().equals(requestPath)){
return true;
}
}
return false;
}
}


4、效果查看

     启动项目之后第一次访问时会调用freeUrlService.findAll()查询数据库,同时将查询结果放入缓存。第二次及后面的访问会直接从缓存中获取已经存入的结果,

不会再去访问数据库。可以通过打印SQL来看,除了第一次访问的时候会查询数据库,后面的查询都是从缓存中获取。

-----------------------------------附录---------我的个人配置----------------------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false">
<diskStore path="java.io.tmpdir" />
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"
diskPersistent="false" diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU" />

<cache name="data-cache" maxElementsInMemory="20" overflowToDisk="false"
eternal="false" timeToIdleSeconds="1800" timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU" transactionalMode="off">
<searchable keys="true" /><!-- 可以根据Key进行查询,查询的Attribute就是keys -->
</cache>
</ehcache>
@Autowired
private CacheManager cacheManager;

Cache cache =cacheManager.getCache("data-cache");
//EhCache中的数据类型是Element,它包含Key,Value和一个版本信息
Element e = new Element(request.getSession().getId(),user , 1);
cache.put(e);

Cache cache =cacheManager.getCache("data-cache");
Element e = cache.get(request.getSession().getId());
SysUser sysUser=(SysUser) e.getObjectValue();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: