spring整合EhCache 缓存Dao

spring整合EhCache 缓存Dao

缓存的键的规则

1.spring中ehcache的配置:
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
  <property name="configLocation" value="classpath:ehcache.xml"/>
   </bean>
<bean id="ehCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
  <property name="cacheManager" ref="cacheManager" />
  <property name="cacheName" value="testCache" />
 </bean>
 
<bean id="userDao" class="cn.demo.dao.impl.UserDaoImpl" parent="baseDao">
  <property name="ehCache" ref="ehCache"></property>
 </bean> 

2.UserDaoImpl改成从缓存或者数据库中获取数据
public class UserDaoImpl extends BaseDao implements IUserDao {
 
 Cache ehCache;

 /**
  * 该方法使用缓存
  */
 public List<UserPO> selectList(UserPO parameter) {
  Cache cache =(Cache)ehCache;
  String className = this.getClass().getName();
  String methodName = "selectList";
  //缓存key的生成
  //Object[] args = new Object[]{BeanMap.create(parameter).values()};
  Collection args = BeanMap.create(parameter).values();
  String cacheKey = CacheKey.getCacheKey(className, methodName, args);
  //ValueWrapper val = cache.get(cacheKey);
  Element val =cache.get(cacheKey);
  if(val== null){
   System.out.println("1.dao**********************");
   List<UserPO> list =super.selectList("cn.demo.dao.IUserDao.queryUsers", parameter);
   //cache.put(cacheKey, list);
   Element ele = new Element(cacheKey, list);
   cache.put(ele);
   return list;
  }
  else{
   System.out.println("2.cache######################");
   return (List<UserPO>)val.getObjectValue();
  }
  
 }
 
 public int insert(Object parameter) {
  return insert("cn.demo.dao.IUserDao.insertUser", parameter);
 }
 
 public int count(UserPO user){
  return this.selectOne("cn.demo.dao.IUserDao.count", user);
 }
 
 public List<UserPO> findUsersOfPage(UserPO user, RowBounds rowBounds){
  return this.getSqlSessionTemplate().selectList("cn.demo.dao.IUserDao.findUsersOfPage", user, rowBounds);
 }

 public void setEhCache(Cache ehCache) {
  this.ehCache = ehCache;
 }

 public Cache getEhCache() {
  return ehCache;
 }
}

3.缓存键的生成类
public class CacheKey {
 public static String getCacheKey(String targetName, String methodName,
   Collection arguments) {
  String cacheName = targetName + "." + methodName + ".";
  int hash = 0;
  if ((arguments != null) && (arguments.size() != 0)) {
   Iterator it = arguments.iterator();
   Object o = null;
   while (it.hasNext()) {
    o=it.next();
    if(o==null)
     continue;
    hash += o.hashCode();
   }
  }
  cacheName = cacheName + hash;
  return cacheName;
 }
}

4.ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
 <!-- 默认的磁盘缓存目录 -->
    <diskStore path="java.io.tmpdir"/>
   
    <!-- EhCache是Hibernate的二级缓存技术之一,可以把查询出来的数据存储在内存或者磁盘,节省下次同样查询语句再次查询数据库,大幅减轻数据库压力 -->
    <!-- 默认缓存策略 -->
    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        overflowToDisk="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120" />
   
     <cache name="testCache"
        maxElementsInMemory="10000"
        eternal="false"
        overflowToDisk="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"
        memoryStoreEvictionPolicy="LFU"/>
       
</ehcache>

<!--
        配置自定义缓存
        maxElementsInMemory:缓存中允许创建的最大对象数
        eternal:缓存中对象是否为永久的,如果是true,超时设置将被忽略,对象从不过期。
        overflowToDisk:内存不足时,是否启用磁盘缓存。
        timeToIdleSeconds:缓存数据的钝化时间,也就是在一个元素消亡之前,
                    两次访问时间的最大时间间隔值,这只能在元素不是永久驻留时有效,
                    如果该值是0,就意味着元素可以停顿无穷长的时间。
                    (即:设置缓存中的对象在过期之前的最大空闲时间,单位秒)
        timeToLiveSeconds:缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,
                    这只能在元素不是永久驻留时有效,如果该值是0,就意味着元素可以停顿无穷长的时间。
                    (即:设置缓存中的对象在过期之前的最大生存时间,单位秒)
        memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。共有三种:FIFO-先进先出,LFO-最少使用的出,LRO-最久没用的出。
 -->

 5.测试是否从缓存中获取数据
 @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/*.xml"})
public class UserDaoEhCacheTest {
 
 @Autowired
 IUserDao userDao;
 
 
 
 /*缓存dao*/
 @Test
 public void testUserDaoCache(){
  
  for(int i=0;i<5;i++){
   userDao();
  }
 }
 
 private void userDao(){
  UserPO po = new UserPO();
  po.setUserName("xx");
  List<UserPO> userList = userDao.selectList(po);
  System.out.println(userList.size());
  for(UserPO u: userList){
   
   if(u.getUserId().startsWith("27"))
   System.out.println(u.getUserId() + " "+u.getUserName());
  }
 }
 
 /*
日志:第一次查询数据库,后面的查询的缓存
1.dao**********************
35
270 wangwu8
271 wangwu8
2.cache######################
35
270 wangwu8
271 wangwu8
2.cache######################
35
270 wangwu8
271 wangwu8
2.cache######################
35
270 wangwu8
271 wangwu8
2.cache######################
35
270 wangwu8
271 wangwu8

  */
 
}
 

猜你喜欢

转载自zw7534313.iteye.com/blog/2253395