天天看点

hibernate使用jboss缓存

第一步:配置

为了使用Hiberante的二级缓存支持集群,可以选择OSCache和JBossCache等,这里我们选择了JBossCache.

JBossCache可以在这里找到http://www.jboss.org/developers/projects/jboss/cache/。

1.Hibernate的配置

(1)在hibernate.cfg.xml中加入下在面的语句,如果有使用了其它的cache请注掉

<property name="hibernate.cache.provider_class">net.sf.hibernate.cache.TreeCacheProvider</property>

(2)在hibernate的映射文件中,在需要缓存的类定义中加入类似下面的语句

<cache usage="nonstrict-read-write"/>,应该改为<cache usage="read-only | transactional"/>usage这个属性根据需要可以改为对应的值(另注:以前这里主要的错误是使用了nonstrict-read-write,而根据HIBERNATE的文档,只能用read-only或taransactional,我记得当时我用了read-wirte,可奇怪得是没有发生问题,郁闷,哪位高人知道请通知我一下)

至此,Hibernate的配置做完

2.JBossCache的配置

首先需要建一个名为treecache.xml的文件,对于web应用,放在WEB-INF下面就行,内容类似下面的内容

代码内容

<?xml version="1.0" encoding="UTF-8"?>

<server>

<mbean code="org.jboss.cache.TreeCache" name="jboss.cache:service=TreeCache">

<attribute name="IsolationLevel">REPEATABLE_READ</attribute>

<!--如果需要集群应该使用REPL_ASYNC或REPL_SYNC,前者是异步复制,而后者是同步复制-->

<attribute name="CacheMode">REPL_SYNC</attribute>

<attributename="ClusterName">clumsterName</attribute>

<attribute name="ClusterConfig">

<config>

<!--在这里配置Jgroup的相关属性,特别要注意的是mcast_addr,这是一个多播地址,这里使用224.0.0.1,是网络中所有支持多播的地址(今天又试了一下,发现可以直接指定有效的多播地址,系统会自动注册这个地址) bind_addr是本机的IP-->

<UDP mcast_addr="224.0.0.1" mcast_port="45566" ip_ttl="64" ip_mcast="true" mcast_send_buf_size="150000" cast_recv_buf_size="80000"

ucast_send_buf_size="150000" ucast_recv_buf_size="80000" loopback="false" bind_addr="192.168.0.2"/>

<PING timeout="2000" num_initial_members="3" up_thread="false" down_thread="false"/>

<MERGE2 min_interval="10000" max_interval="20000"/>

<FD shun="true" up_thread="true" down_thread="true"/>

<VERIFY_SUSPECT timeout="1500" up_thread="false" down_thread="false"/>

<pbcast.NAKACK gc_lag="50" retransmit_timeout="600,1200,2400,4800"

up_thread="false" down_thread="false"/>

<pbcast.STABLE desired_avg_gossip="20000" up_thread="false" down_thread="false"/>

<UNICAST timeout="600,1200,2400" window_size="100" min_threshold="10" down_thread="false"/>

<FRAG frag_size="8192" down_thread="false" up_thread="false"/>

<pbcast.GMS join_timeout="5000" join_retry_timeout="2000"

shun="true" print_local_addr="true"/>

<pbcast.STATE_TRANSFER up_thread="false" down_thread="false"/>

</config>

</attribute>

<attribute name="MaxCapacity">20000</attribute>

<attribute name="InitialStateRetrievalTimeout">20000</attribute>

<attribute name="SyncReplTimeout">10000</attribute>

<attribute name="LockAcquisitionTimeout">15000</attribute>

<attribute name="LockLeaseTimeout">60000</attribute>

<attribute name="EvictionPolicyClass">org.jboss.cache.eviction.LRUPolicy</attribute>

<attribute name="EvictionPolicyConfig">

<config>

<attribute name="wakeUpIntervalSeconds">15</attribute>

<region name="/_default_">

<attribute name="maxNodes">5000</attribute>

<attribute name="timeToIdleSeconds">1000</attribute>

</region>

</config>

</attribute>

</mbean>

</server>