hibernate中使用分布式ehcache

swsan 2013-04-02

最近没什么事,研究了下分布式缓存Ehcache.

一、下载

    从terracotta.org上下载terracotta-3.7.5-installer.jar,然后使用java -jar命令来安装它。

在安装目录的bin目录terracotta-3.7.5\bin下运行start-tc-server.bat文件来启动terracotta

 

二、客户端:

需要的JAR包:

在terracotta安装目录中找到terracotta-3.7.5\ehcache\lib\下的文件:

ehcache-core-2.6.6.jar(建议不要使用与terracotta不匹配的ehcache版本,如ehche-core-2.7.0,否则可能客户端代码出现异常)

ehcache-terracotta-2.6.6.jar

在terracotta安装目录中找到common\terracotta-toolkit-1.6-runtime-5.5.0.jar

然后加上日志包:slf4j-api、slf4j-log4j、log4j

 

配置文件:

log4j.properties

ehcache.xml

<cache name="terracottaCacheTest"

    maxEntriesLocalHeap="1000"

    eternal="false"

    timeToIdleSeconds="3600"

    timeToLiveSeconds="1800"

    overflowToDisk="false">

    <terracotta/>

</cache>

 

 

测试类:

publicclass TerracottaExample

{

    CacheManager cacheManager = new CacheManager();

 

    public TerracottaExample()

    {

       Cache cache = cacheManager.getCache("terracottaCacheTest");

       int cacheSize = cache.getKeys().size();

       cache.put(new Element("" + cacheSize, cacheSize));

       for (Object key : cache.getKeys())

       {

           System.out.println("Key:" + key+",value:"+cache.get(key).getObjectValue());

       }

       cacheManager.shutdown();

    }

 

    publicstaticvoid main(String[] args) throws Exception

    {

       new TerracottaExample();

    }

}

 

三、在Hibernate中使用分布式二级缓存

加入hibernate4.2.0的Jar包

加入mysql-connector-java-5.1.24-bin.jar

添加Hibernate.cfg.xml文件:如下

<session-factory>

    <!-- SQL dialect -->

    <property name="hibernate.dialect">

       org.hibernate.dialect.MySQL5InnoDBDialect

    </property>

    <!-- Database connection settings -->

    <property name="connection.driver_class">

       com.mysql.jdbc.Driver

    </property>

    <property name="connection.url">jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8</property>

    <property name="connection.username">root</property>

    <property name="connection.password">123456</property>

    <property name="hbm2ddl.auto">update</property>

    <property name="javax.persistence.validation.mode">none</property>

 

    <!-- JDBC connection pool (use the built-in) -->

    <property name="connection.pool_size">1</property>

 

    <property name="hibernate.cache.use_second_level_cache">true</property>

    <property name="hibernate.cache.use_query_cache">true</property>

    <property name="hibernate.cache.region.factory_class">

       org.hibernate.cache.ehcache.EhCacheRegionFactory

    </property>

    <property name="jdbc.batch_size">50</property>

 

    <!-- Echo all executed SQL to stdout -->

    <property name="show_sql">true</property>

    <property name="current_session_context_class">thread</property>

    <!-- Names the annotated entity class -->

    <mapping class="bean.Student"/>

</session-factory>

 

创建Bean

@Entity

@Table(name="student")

@Cache(usage=CacheConcurrencyStrategy.READ_WRITE,region="terracottaCacheTest")//这里的区域仍然使用terracottaCacheTest,当hibernate操作数据时,可以查看此缓存区域中是否有加入了缓存中。

publicclass Student implements Serializable

{

    privatestaticfinallongserialVersionUID = -2482463021057396397L;

    privateintid;

    private String name;

//省略get、set方法

}

 

测试类

 

Configuration cfg=new Configuration().configure();//加载配置文件hibernate.cfg.xml

ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();//ServiceRegistryBuilder通过配置文件的参数来建立相应的ServiceRegistry!

       SessionFactory sessionFactory =cfg.buildSessionFactory(serviceRegistry);//建立SessionFactory

      

       Session session=sessionFactory.getCurrentSession();

       Transaction transaction=session.beginTransaction();

       try{

           Student student=(Student)session.get(Student.class, 1);

           System.out.println(student.getName());

          

           transaction.commit();

       }catch (Exception e) {

           transaction.rollback();

       }//    finally{//事务在提交或回滚的时候会检测Session是否关闭,如果没有则

//         if(session!=null&&session.isOpen())

//         {

//            System.out.println("关闭Session……");

//            session.close();

//         }

//     }     

      

       sessionFactory.close();

然后运行TerracottaExample这个类,这会发现通过hibernate使用分布式ehcache已经生效!

下面是打印缓存中的内容 

Key:bean.Student#1,value:org.hibernate.cache.ehcache.internal.strategy.AbstractReadWriteEhcacheAccessStrategy$Item@a03a12

 

 国内首套免费的《大数据技术(Hadoop)视频教程》:

http://www.youku.com/playlist_show/id_19172734.html

相关推荐