如何使用hibernate二级缓存及在必要的时候联机清除cache (这个有用)

    入门使用cache很简单。
1/ 在 classpath根下建 ehcache.xml 内容如下:
<ehcache>   
     <diskStore path="java.io.tmpdir"/>    

     <defaultCache
         maxElementsInMemory="10000"
         eternal="false"
         overflowToDisk="true"
         timeToIdleSeconds="120"
         timeToLiveSeconds="120"
         diskPersistent="false"
         diskExpiryThreadIntervalSeconds="120"/>       
    
</ehcache>


2/ 修改需要使用缓存的对象所对应的hbm.xml文件。加入 <cache usage="read-only"/>标记。

3/ 默认情况下,load是使用缓存的。 但一般是使用find或者list方法来取得数据。所以按如下操作:
   修改 hibernate.cfg.xml 加入
   <property name="show_sql">true</property>
  <property name="hibernate.cache.use_query_cache">true</property>
        <property name="hibernate.cache.use_second_level_cache">true</property>
        <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>

4/ 在DAO的代码中使用
  Session session = sf.openSession();
  try {
   
   Query query = session.createQuery("from StockInfo where id = ?");
   query.setLong(0, 1800);
   query.setCacheable(true);
   query.list();
   session.close();
      
   session = sf.openSession();
   query = session.createQuery("from StockInfo where id = ?");
   query.setLong(0, 1800);
   query.setCacheable(true);
   query.list();
  } catch (Exception ex) {
   log.info(ex.getMessage(), ex);
  }
你会发现只会打印出一条SQL语句。 证明使用了缓存功能。

下面是关键的另一步了。 在系统中,由于程序的bug或者特殊情况需要直接修改数据库 而又不允许停机。 这时候,如果你的cache规则定义的好, 那么只影响那么几毫秒。 但有规则的定义未必那么全面。 这时候就需要:使用SQL语句修改后台数据库之后,需要清空application的缓存,从而让hibernate到数据库中取到最新的 修改之后的值
   hibernate好像没有提供直接的清除cache的方法(我没找到)。所以使用下面的函数:
   sf 是 application中的sessionfactory。
   public static void evictSecondLevelCache() {
    Map<String, CollectionMetadata> roleMap = sf.getAllCollectionMetadata();
    for (String roleName : roleMap.keySet()) {
      sf.evictCollection(roleName);
    }

    Map<String, ClassMetadata> entityMap = sf.getAllClassMetadata();
    for (String entityName : entityMap.keySet()) {
      sf.evictEntity(entityName);
    }

    sf.evictQueries();
 }

示例:
Session session = sf.openSession();
  try {
   
   Query query = session.createQuery("from StockInfo where id = ?");
   query.setLong(0, 1800);
   query.setCacheable(true);
   query.list();
   session.close();
   
   evictSecondLevelCache();
   
   session = sf.openSession();
   query = session.createQuery("from StockInfo where id = ?");
   query.setLong(0, 1800);
   query.setCacheable(true);
   query.list();
  } catch (Exception ex) {
   log.info(ex.getMessage(), ex);
  }

就会在控制台中发现打印出两条SQL语句。 实际中可以把 evictSecondLevelCache();
放到一个单独的管理页面中。 叫“清除缓存”功能。 专门为 手动修改数据库 后的数据同步做准备。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值