cyrus 发表于 2015-11-18 13:07:48

memcached分布式缓存和hibernate结合-- Hibernate+ehcache二级缓存技术

Memcached是由Danga Interactive开发的,高性能的,分布式的内存对象缓存系统,用于在动态应用中减少数据库负载,提升访问速度。Memcached 的缓存是一种分布式的,可以让不同主机上的多个用户同时访问, 因此解决了共享内存只能单机应用的局限,更不会出现使用数据库做类似事情的时候,磁盘开销和阻塞的发生。
memcached的使用
一 Memcached服务器端的安装 (此处将其作为系统服务安装)
下载文件:memcached 1.2.1 for Win32 binaries (Dec 23,2006)
   1 解压缩文件到c:\memcached
   2 命令行输入 'c:\memcached\memcached.exe -d install'
   3 命令行输入 'c:\memcached\memcached.exe -d start' ,该命令启动 Memcached ,默认监听端口为 11211
通过 memcached.exe -h 可以查看其帮助
问题
  如果没有下载服务器端(如果memcached的使用)开启memcached服务的话,那么将出现一系列的错误,最主要是报连接的问题。所以大家在使用memcached的时候一定要安装服务器端。
memcached和Hibernate的结合
现在Hibernate实现了memcached的无缝连接,已经说过了,hibernate暴力的地方是他的缓存,hibernate结合memcached也是相当方便,只需配置,启动服务器没有错误算配置OK啦。去在网上看了一大堆关于hibernate和memcached结合的文章,文章内容基本上都是一致的,郁闷死,参考价值就少了很多。本人公司正使用memcached作为Hibernate的二级缓存,在这里也整理一下相关的内容。
  hibernate的缓存机制是其成为主流持久层霸主地位的重要组成部分,他的缓存机制是很黄很暴力的。二级缓存是SessionFactory级别的全局缓存,可以通过配置文件的hibernate.cache.provider_class 进行指定。在上次的日志上有提到相关的配置,在这里我再次贴一次供需要的人了解。
hibernate.cfg.xml
代码
<?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?>
<!DOCTYPE hibernate-configuration PUBLIC &quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot;
                                          &quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&quot;>
<hibernate-configuration>
<session-factory name=&quot;default&quot;>
   <property name=&quot;hibernate.show_sql&quot;>true</property>
   <property name=&quot;hibernate.format_sql&quot;>true</property>
   <property name=&quot;hibernate.hbm2ddl.auto&quot;>update</property>
   <!-- <property name=&quot;hibernate.dialect&quot;>org.hibernate.dialect.MySQLDialect</property> -->
   <property name=&quot;hibernate.dialect&quot;>org.hibernate.dialect.Oracle10gDialect</property>
   <property name=&quot;hibernate.jdbc.fetch_size&quot;>50</property>
   <property name=&quot;hibernate.jdbc.batch_size&quot;>0</property>
   <property name=&quot;hibernate.default_schema&quot;>user</property>
   
      <!-- hibernate-memcache配置-->
      <!-- 开启二级缓存-->
   <property name=&quot;hibernate.cache.use_second_level_cache&quot;>
         true   
   </property>
   <!-- 设置缓存类-->
   <property name=&quot;hibernate.cache.provider_class&quot;>com.googlecode.hibernate.memcached.MemcachedCacheProvider</property>
   <!-- 设置memcache缓存服务器端口 -->
   <property name=&quot;hibernate.memcached.servers&quot;>localhost:11211</property>
   <!-- 设置二级缓存的前缀名称 -->
   <property name=&quot;hibernate.cache.region_prefix&quot;>quality.cache.ehcache</property>
   <!-- 否使用结构化的方式缓存对象-->
   <property name=&quot;hibernate.cache.use_structured_entries&quot;>true</property>
   <!-- 是否缓存查询结果 -->
   <property name=&quot;hibernate.cache.use_query_cache&quot;>true</property>

   <mapping resource=&quot;com/weiruan/projs/mydc/pojos/Usert.hbm.xml&quot;/>
   <mapping resource=&quot;com/weiruan/projs/mydc/pojos/Developer.hbm.xml&quot;/>
</session-factory>
</hibernate-configuration>



依赖的包:hibernate-memcache.jar,memcached-2.3.1.jar、spy2.4、slf4j-1.5.0.jar、slf4j-log4j12-1.5.0.jar还有一个hibernate-memcached[版本].jar,下载地址:http://code.google.com/p/hibernate-memcached/downloads/list。






  1、首先设置EhCache,建立配置文件ehcache.xml,默认的位置在class-path,可以放到你的src目录下:
  <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?>
<ehcache>
 <diskStore path=&quot;java.io.tmpdir&quot;/>
  <defaultCache
   maxElementsInMemory=&quot;10000&quot; <!-- 缓存最大数目 -->
   eternal=&quot;false&quot; <!-- 缓存是否持久 -->
   overflowToDisk=&quot;true&quot; <!-- 是否保存到磁盘,当系统当机时-->
   timeToIdleSeconds=&quot;300&quot; <!-- 当缓存闲置n秒后销毁 -->
   timeToLiveSeconds=&quot;180&quot; <!-- 当缓存存活n秒后销毁-->
   diskPersistent=&quot;false&quot;
   diskExpiryThreadIntervalSeconds= &quot;120&quot;/>
</ehcache>

  2、在Hibernate配置文件中设置:

  <!-- 设置Hibernate的缓存接口类,这个类在Hibernate包中 -->
<property name=&quot;cache.provider_class&quot;>org.hibernate.cache.EhCacheProvider</property>
 <!-- 是否使用查询缓存 -->
 <property name=&quot;hibernate.cache.use_query_cache&quot;>true</property>
  如果使用spring调用Hibernate的sessionFactory的话,这样设置:
  <!--HibernateSession工厂管理 -->
   <bean id=&quot;sessionFactory&quot; class=&quot;org.springframework.orm.hibernate3.LocalSessionFactoryBean&quot;>
   <property name=&quot;dataSource&quot;>
    <ref bean=&quot;datasource&quot; />
   </property>
   <property name=&quot;hibernateProperties&quot;>
   <props>
    <prop key=&quot;hibernate.dialect&quot;>org.hibernate.dialect.Oracle9Dialect</prop>
    <prop key=&quot;connection.provider_class&quot;>org.hibernate.connection.C3P0ConnectionProvider</prop>
    <prop key=&quot;hibernate.show_sql&quot;>true</prop>
    <prop key=&quot;hibernate.cache.use_query_cache&quot;>true</prop>
    <prop key=&quot;hibernate.cache.provider_class&quot;>org.hibernate.cache.EhCacheProvider</prop>
   </props>
 </property>
 <property name=&quot;mappingDirectoryLocations&quot;>
  <list>
   <value>/WEB-INF/classes/cn/rmic/manager/hibernate/</value>
  </list>
 </property>
</bean>

  说明一下:如果不设置“查询缓存”,那么hibernate只会缓存使用load()方法获得的单个持久化对象,如果想缓存使用findall()、list()、Iterator()、createCriteria()、createQuery()等方法获得的数据结果集的话,就需要设置
hibernate.cache.use_query_cache true 才行

3、在Hbm文件中添加<cache usage=&quot;read-only&quot;/>

4、如果需要“查询缓存”,还需要在使用Query或Criteria()时设置其setCacheable(true);属性

5、实践出真知,给一段测试程序,如果成功的话第二次查询时不会读取数据库

  package cn.rmic.hibernatesample;
import java.util.List;


import org.hibernate.CacheMode;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;


import cn.rmic.hibernatesample.hibernate.HibernateSessionFactory;
import cn.rmic.manager.po.Resources;


public class testCacheSelectList ...{


 /** *//**
 * @param args
 */
 public static void main(String[] args) ...{
  // TODO Auto-generated method stub


  Session s=HibernateSessionFactory.getSession();
  Criteria c=s.createCriteria(Resources.class);
  c.setCacheable(true);
  List l=c.list();
  // Query q=s.createQuery(&quot;From Resources r&quot;)
  // .setCacheable(true)
  // .setCacheRegion(&quot;frontpages&quot;) ;
  // List l=q.list();
  Resources resources=(Resources)l.get(0);
  System.out.println(&quot;-1-&quot;&#43;resources.getName());
  HibernateSessionFactory.closeSession();
  try ...{
   Thread.sleep(5000);
  } catch (InterruptedException e) ...{
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  s=HibernateSessionFactory.getSession();
  c=s.createCriteria(Resources.class);
  c.setCacheable(true);
  l=c.list();
  // q=s.createQuery(&quot;From Resources r&quot;).setCacheable(true)
  // .setCacheRegion(&quot;frontpages&quot;);
  // l=q.list();
  resources=(Resources)l.get(0);
  System.out.println(&quot;-2-&quot;&#43;resources.getName());
  HibernateSessionFactory.closeSession();
 }
页: [1]
查看完整版本: memcached分布式缓存和hibernate结合-- Hibernate+ehcache二级缓存技术