java缓存详解

  • 格式:pdf
  • 大小:133.94 KB
  • 文档页数:8

Ehcache中不仅可以用配置文件来配置缓存,而在代码中也可以实现同样的功能。

CacheManager singletonManager=CacheManager.create();Cache memoryOnlyCache=new Cache(“testCache”,50000,false,false,8,2);Cache test=singletonManager.getCache(“testCache”);删除只需要调用singletonManager.removeCache(“testCache”);Shotdown CacheManager在使用完Ehcache后,必须要shutdown缓存。

Ehcache中有自己的关闭机制,不过最好在你的代码中显示调用CacheManager.getInstance().shutdown();1.EhCache是什么EhCache是Hibernate的二级缓存技术之一,可以把查询出来的数据存储在内存或者磁盘,节省下次同样查询语句再次查询数据库,大幅减轻数据库压力;2.EhCache的使用注意点当用Hibernate的方式修改表数据(save,update,delete等等),这时EhCache会自动把缓存中关于此表的所有缓存全部删除掉(这样能达到同步)。

但对于数据经常修改的表来说,可能就失去缓存的意义了(不能减轻数据库压力);3.EhCache使用的场合3.1比较少更新表数据EhCache一般要使用在比较少执行write操作的表(包括update,insert,delete等)[Hibernate的二级缓存也都是这样];3.2对并发要求不是很严格的情况两台机子中的缓存是不能实时同步的;4.在项目做的实现4.1在工程的src目录下添加ehcache.xml文件,内容如下:<?xml version="1.0"encoding="UTF-8"?><ehcache><diskStore path="java.io.tmpdir"/><defaultCache maxElementsInMemory="5"<!--缓存可以存储的总记录量-->eternal="false"<!--缓存是否永远不销毁-->overflowToDisk="true"<!--当缓存中的数据达到最大值时,是否把缓存数据写入磁盘-->timeToIdleSeconds="15"<!--当缓存闲置时间超过该值,则缓存自动销毁-->timeToLiveSeconds="120"<!--缓存创建之后,到达该缓存自动销毁-->/></ehcache>4.2在Hibernate.cfg.xml中的mapping标签上面加以下内容:<property name="show_sql">true</property><propertyname="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> <property name="e_query_cache">true</property>4.3在要缓存的bean的hbm.xml文件中的class标签下加入以下内容:<cache usage="read-only"/><!--也可读写-->4.4创建DAO,内容如下:Session s=HibernateSessionFactory.getSession();Criteria c=s.createCriteria(Xyz.class);c.setCacheable(true);//这句必须要有System.out.println("第一次读取");List l=c.list();System.out.println(l.size());HibernateSessionFactory.closeSession();s=HibernateSessionFactory.getSession();c=s.createCriteria(Xyz.class);c.setCacheable(true);//这句必须要有System.out.println("第二次读取");l=c.list();System.out.println(l.size());HibernateSessionFactory.closeSession();4.5这时你会看到打印出来的信息为(表示第二次并没有去读库):第一次读取Hibernate:*******13第二次读取13配置Spring+hibernate使用ehcache作为second-level cache大量数据流动是web应用性能问题常见的原因,而缓存被广泛的用于优化数据库应用。

cache被设计为通过保存从数据库里load的数据来减少应用和数据库之间的数据流动。

数据库访问只有当检索的数据不在cache里可用时才必要。

hibernate可以用两种不同的对象缓存:first-level cache和second-level cache。

first-level cache和Session对象关联,而second-level cache是和Session Factory对象关联。

缺省地,hibernate已经使用基于每个事务的first-level cache。

Hibernate用first-level cache主要是减少在一个事务内的sql查询数量。

例如,如果一个对象在同一个事务内被修改多次,hibernate将只生成一个包括所有修改的UPDATE SQL语句。

为了减少数据流动,second-level cache在Session Factory 级的不同事务之间保持load的对象,这些对象对整个应用可用,不只是对当前用户正在运行的查询。

这样,每次查询将返回已经load在缓存里的对象,避免一个或更多潜在的数据库事务。

下载ehcache,hibernate3.2必须要ehcache1.2以上才能支持。

可以修改log4j配置文件.sf.hibernate.cache=debug查看日志1.在类路径上ehcache.xml:<ehcache><!--Sets the path to the directory where cache.data files are created.If the path is a Java System Property it is replaced byits value in the running VM.The following properties are translated:user.home-User's home directoryuser.dir-User's current working directoryjava.io.tmpdir-Default temp file path--><diskStore path="java.io.tmpdir"/><!--Default Cache configuration.These will applied to caches programmatically created through the CacheManager.The following attributes are required:maxElementsInMemory-Sets the maximum number of objects that will be created in memoryeternal-Sets whether elements are eternal.If eternal,timeouts are ignored and theelement is never expired.overflowToDisk-Sets whether elements can overflow to disk when the in-memorycachehas reached the maxInMemory limit.The following attributes are optional:timeToIdleSeconds-Sets the time to idle for an element before it expires.i.e.The maximum amount of time between accesses before an element expiresIs only used if the element is not eternal.Optional attribute.A value of0means that an Element can idle for infinity.The default value is0.timeToLiveSeconds-Sets the time to live for an element before it expires.i.e.The maximum time between creation time and when an element expires.Is only used if the element is not eternal.Optional attribute.A value of0means that and Element can live for infinity.The default value is0.diskPersistent-Whether the disk store persists between restarts of the Virtual Machine.The default value is false.diskExpiryThreadIntervalSeconds-The number of seconds between runs of the disk expiry thread. The default valueis120seconds.--><defaultCachemaxElementsInMemory="10000"eternal="false"overflowToDisk="true"timeToIdleSeconds="120"timeToLiveSeconds="120"diskPersistent="false"diskExpiryThreadIntervalSeconds="120"/><!--See /documentation/#mozTocId258426for how to configure caching for your objects--></ehcache>2.applicationContext-hibernate.xml里Hibernate SessionFactory配置:<!--Hibernate SessionFactory--><bean id="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"ref="dataSource"/><property name="configLocation"><value>classpath:hibernate.cfg.xml</value></property><!--The property below is commented out b/c it doesn't work when run viaAnt in Eclipse.It works fine for individual JUnit tests and in IDEA??<property name="mappingJarLocations"><list><value>file:dist/appfuse-dao.jar</value></list></property>--><property name="hibernateProperties"><props><prop key="hibernate.dialect">@HIBERNATE-DIALECT@</prop><!--<prop key="hibernate.show_sql">true</prop>--><prop key="hibernate.max_fetch_depth">3</prop><prop key="e_outer_join">true</prop><prop key="hibernate.jdbc.batch_size">10</prop><prop key="e_query_cache">true</prop><prop key="e_second_level_cache">true</prop><propkey="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop> <!--<prop key="e_sql_comments">false</prop>--><!--Create/update the database tables automatically when the JVM starts up<prop key="hibernate.hbm2ddl.auto">update</prop>--><!--Turn batching off for better error messages under PostgreSQL<prop key="hibernate.jdbc.batch_size">0</prop>--></props></property><property name="entityInterceptor"><ref local="auditLogInterceptor"/></property></bean>说明:如果不设置“查询缓存”,那么hibernate只会缓存使用load()方法获得的单个持久化对象,如果想缓存使用findall()、list()、Iterator()、createCriteria()、createQuery()等方法获得的数据结果集的话,就需要设置e_query_cache true才行3.model类里采用Xdoclet生成*.hbm.xml里的cache xml标签,即<cache usage="read-only"/>/***@hibernate.class table="WF_WORKITEM_HIS"*@hibernate.cache usage="read-write"**/4.对于"query cache",需要在程序里编码:getHibernateTemplate().setCacheQueries(true);return getHibernateTemplate().find(hql);使用spring和hibernate配置ehcache和query cache1、applicationContext.xml<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop><prop key="e_query_cache">true</prop>这两句加到hibernateProperties中<bean id="hibernateTemplate"class="org.springframework.orm.hibernate3.HibernateTemplate"><property name="sessionFactory"><ref bean="sessionFactory"/></property><property name="cacheQueries"><value>true</value></property></bean>添加此bean到applicationcontext.xml中。