JBoss Cache for Spring(Declarative Caching Services)

本文介绍了一个使用JBossCache、Spring及Spring Modules Cache进行缓存管理的示例项目。项目包括了必要的配置文件、代码实现及测试流程。通过该示例可以了解如何在Java应用程序中集成并使用这些技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、开发环境

Eclipse 3.3

JDK 5.0+JBoss Cache 1.2.4+Spring 2.0+springmodels 0.8

二、配置文件

1、  JBoss Cache配置文件

treecache.xml:

<server>

    <mbean code="org.jboss.cache.TreeCache"

        name="jboss.cache:service=TreeCache">

        <depends>jboss:service=Naming</depends>

        <depends>jboss:service=TransactionManager</depends>

        <attribute name="ClusterName">TreeCache-Cluster</attribute>

        <attribute name="ClusterConfig">

            <config>

                <UDP mcast_addr="228.1.2.3" mcast_port="48866"

                    ip_ttl="64" ip_mcast="true" mcast_send_buf_size="150000"

                    mcast_recv_buf_size="80000" ucast_send_buf_size="150000"

                    ucast_recv_buf_size="80000" loopback="false" />

                <PING timeout="2000" num_initial_members="3"

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

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

                <FD_SOCK />

                <VERIFY_SUSPECT timeout="1500" up_thread="false"

                    down_thread="false" />

                <pbcast.NAKACK gc_lag="50"

                    retransmit_timeout="600,1200,2400,4800" max_xmit_size="8192"

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

                <UNICAST timeout="600,1200,2400" window_size="100"

                    min_threshold="10" down_thread="false" />

                <pbcast.STABLE desired_avg_gossip="20000"

                    up_thread="false" 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="true"

                    down_thread="true" />

            </config>

        </attribute>

    </mbean>

</server>

注意:treecache.xml中红色字体将是我们需要应用的部分!

2、  Spring配置文件

cache.xml:

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

<beans xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns:coherence="http://www.springmodules.org/schema/coherence"

    xsi:schemaLocation="http://www.springframework.org/schema/beans

         http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

 

    <bean id="User" class="com.cache.model.UserImpl">

        <property name="usernames">

            <list>

                <value>Luke Skywalker</value>

                <value>Leia Organa</value>

            </list>

        </property>

    </bean>

 

    <bean id="UserService" class="com.cache.service.UserServiceImpl">

        <property name="users">

            <ref local="User" />

        </property>

    </bean>

 

    <bean id="cacheManager"

        class="org.springmodules.cache.provider.jboss.JbossCacheManagerFactoryBean">

        <property name="configLocation" value="classpath:treecache.xml" />

        <!-- Optional properties -->

    </bean>

 

    <bean id="cacheProviderFacade"

        class="org.springmodules.cache.provider.jboss.JbossCacheFacade">

        <property name="cacheManager" ref="cacheManager" />

    </bean>

 

    <bean id="cachingListener"

        class="com.cache.Listener.CachingListenerImpl" />

 

    <bean id="cachingInterceptor"

        class="org.springmodules.cache.interceptor.caching.MethodMapCachingInterceptor">

        <property name="cacheProviderFacade" ref="cacheProviderFacade" />

        <!-- 此Demo中cachingListener可不使用 -->

        <property name="cachingListeners">

            <list>

                <ref bean="cachingListener" />

            </list>

        </property>

 

        <property name="cachingModels">

            <props>

                <prop key="com.cache.service.UserService.load*">

                    node=jboss.cache:service=TreeCache

                </prop>

            </props>

        </property>

    </bean>

 

    <bean id="flushingInterceptor"

        class="org.springmodules.cache.interceptor.flush.MethodMapFlushingInterceptor">

        <property name="cacheProviderFacade" ref="cacheProviderFacade" />

        <property name="flushingModels">

            <props>

                <prop key="com.cache.service.UserService.update*">

                    nodes=jboss.cache:service=TreeCache

                </prop>

            </props>

        </property>

    </bean>

    <bean

        class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">

        <property name="beanNames">

            <list>

                <idref local="UserService" />

            </list>

        </property>

        <property name="interceptorNames">

            <list>

                <value>cachingInterceptor</value>

                <value>flushingInterceptor</value>

            </list>

        </property>

    </bean>

</beans>

说明:1、<property name="configLocation" value="classpath:treecache.xml" />

                 在cacheManager中引入JBoss Cache配置文件

           2、<prop key="com.cache.service.UserService.load*">

                 此处应写接口方法,而不是实现类方法,因为在此Demo中getBean()方法返回的是接口类型!

           3、node=jboss.cache:service=TreeCache

                nodes=jboss.cache:service=TreeCache   

                此处引入treecahce.xml中红色字体部分,注意cachingModels中属性名为node,而flushModeling中

                属性名为nodes!

3、日志文件

log4j.properties:

log4j.rootLogger=DEBUG, stdout
       log4j.appender.stdout=org.apache.log4j.ConsoleAppender
       log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
       log4j.appender.stdout.layout.ConversionPattern=%c{1} - %m%n

三、Java Demo

1、类CachingListenerImpl:只是单纯实现了CachingListener接口,此Demo中可不使用此类,同时将cache.xml配置文件中蓝色字体部分删去即可。

package com.cache.Listener;
       import java.io.Serializable;

import org.springmodules.cache.CachingModel;
       import org.springmodules.cache.interceptor.caching.CachingListener;

public class CachingListenerImpl implements CachingListener {

      public void onCaching(Serializable arg0, Object arg1, CachingModel arg2) {}

}

2、接口User

package com.cache.model;

import java.util.List;

public interface User { 
             public abstract List<String> getUsernames(); 
             public abstract void setUsernames(List<String> usernames);

}

3、类UserImpl

package com.cache.model;

import java.util.List;

public class UserImpl implements User{

      private List<String> usernames;

      public List<String> getUsernames() {
                   return usernames;
             }

      public void setUsernames(List<String> usernames) {
                   this.usernames = usernames;
             }

}

4、接口UserService

package com.cache.service;

import java.util.List;

import com.cache.model.User;

public interface UserService { 
             public List<String> load(); 
             public User changeUsers(); 
             public User changeUsers2(); 
             public void update(); 
       }

5、类UserServiceImpl

package com.cache.service;

import java.util.ArrayList;
       import java.util.List;

import com.cache.model.User;

public class UserServiceImpl implements UserService {

      private User users;

      public User getUsers() {
                   return users;
             }

      public void setUsers(User users) {
                   this.users = users;
             }

      //caching方法

      public List<String> load() {
                   return users.getUsernames();
             }

      public User changeUsers() {
                   List<String> newUserList = new ArrayList<String>();
                   newUserList.add(0, "Anson Yang");
                   newUserList.add(1, "Kelly Chen");
                   users.setUsernames(newUserList);
                   return users;
             }
 
             public User changeUsers2() {
                   List<String> newUserList = new ArrayList<String>();
                   newUserList.add(0, "Clark Li");
                   newUserList.add(1, "Grant Ling");
                   users.setUsernames(newUserList);
                   return users;
             }

      //flushing方法

      public void update() {}

}

6、测试类SimpleTest

package com.cache.test;

import org.springframework.context.ApplicationContext;
       import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.cache.service.UserService;

public class SimpleTest {
             public static void main(String[] args){
                   ApplicationContext ctx = new ClassPathXmlApplicationContext("cache.xml");
                   UserService userService = (UserService) ctx.getBean("UserService");
                   System.out.println("----------------------load()----------------------------");
                   System.out.println(userService.load());
                   System.out.println("------------------changeUsers()-------------------------");
                   userService.changeUsers();
                   System.out.println("----------------------load()----------------------------");
                   System.out.println(userService.load());
                   System.out.println("---------------------update()---------------------------");
                   userService.update();
                   System.out.println("----------------------load()----------------------------");
                   System.out.println(userService.load());
                   System.out.println("------------------changeUsers2()-------------------------");
                   userService.changeUsers2();
                   System.out.println("----------------------load()----------------------------");
                   System.out.println(userService.load());
                   System.out.println("---------------------update()---------------------------");
                   userService.update();
                   System.out.println("----------------------load()----------------------------");
                   System.out.println(userService.load());
             }
       }

 

7、测试结果


----------------------load()----------------------------
JbossCacheFacade - Attempt to retrieve a cache entry using key <28400024|28399250> and cache model <org.springmodules.cache.provider.jboss.JbossCacheCachingModel@4aa0ce[nodeFqn='jboss.cache:service=TreeCache']>
JbossCacheFacade - Retrieved cache element <null>
MethodMapFlushingInterceptor - Unable to flush cache. No model is associated to the intercepted method
JbossCacheFacade - Attempt to store the object <[Luke Skywalker, Leia Organa]> in the cache using key <28400024|28399250> and model <org.springmodules.cache.provider.jboss.JbossCacheCachingModel@4aa0ce[nodeFqn='jboss.cache:service=TreeCache']>
JbossCacheFacade - Object was successfully stored in the cache
[Luke Skywalker, Leia Organa]
------------------changeUsers()-------------------------
MethodMapCachingInterceptor - Unable to perform caching. No model is associated to the method <public abstract com.cache.model.User com.cache.service.UserService.changeUsers()>
MethodMapFlushingInterceptor - Unable to flush cache. No model is associated to the intercepted method
----------------------load()----------------------------
JbossCacheFacade - Attempt to retrieve a cache entry using key <28400024|28399250> and cache model <org.springmodules.cache.provider.jboss.JbossCacheCachingModel@4aa0ce[nodeFqn='jboss.cache:service=TreeCache']>
JbossCacheFacade - Retrieved cache element <[Luke Skywalker, Leia Organa]>
[Luke Skywalker, Leia Organa]
---------------------update()---------------------------
MethodMapCachingInterceptor - Unable to perform caching. Intercepted method <public abstract void com.cache.service.UserService.update()> does not return a value
JbossCacheFacade - Attempt to flush the cache using model <org.springmodules.cache.provider.jboss.JbossCacheFlushingModel@145f0e3[nodes={'jboss.cache:service=TreeCache'}, flushBeforeMethodExecution=false]>
JbossCacheFacade - Cache has been flushed.
----------------------load()----------------------------
JbossCacheFacade - Attempt to retrieve a cache entry using key <28400024|28399250> and cache model <org.springmodules.cache.provider.jboss.JbossCacheCachingModel@4aa0ce[nodeFqn='jboss.cache:service=TreeCache']>
JbossCacheFacade - Retrieved cache element <null>
MethodMapFlushingInterceptor - Unable to flush cache. No model is associated to the intercepted method
JbossCacheFacade - Attempt to store the object <[Anson Yang, Kelly Chen]> in the cache using key <28400024|28399250> and model <org.springmodules.cache.provider.jboss.JbossCacheCachingModel@4aa0ce[nodeFqn='jboss.cache:service=TreeCache']>
JbossCacheFacade - Object was successfully stored in the cache
[Anson Yang, Kelly Chen]
------------------changeUsers2()-------------------------
MethodMapCachingInterceptor - Unable to perform caching. No model is associated to the method <public abstract com.cache.model.User com.cache.service.UserService.changeUsers2()>
MethodMapFlushingInterceptor - Unable to flush cache. No model is associated to the intercepted method
----------------------load()----------------------------
JbossCacheFacade - Attempt to retrieve a cache entry using key <28400024|28399250> and cache model <org.springmodules.cache.provider.jboss.JbossCacheCachingModel@4aa0ce[nodeFqn='jboss.cache:service=TreeCache']>
JbossCacheFacade - Retrieved cache element <[Anson Yang, Kelly Chen]>
[Anson Yang, Kelly Chen]
---------------------update()---------------------------
MethodMapCachingInterceptor - Unable to perform caching. Intercepted method <public abstract void com.cache.service.UserService.update()> does not return a value
JbossCacheFacade - Attempt to flush the cache using model <org.springmodules.cache.provider.jboss.JbossCacheFlushingModel@145f0e3[nodes={'jboss.cache:service=TreeCache'}, flushBeforeMethodExecution=false]>
JbossCacheFacade - Cache has been flushed.
----------------------load()----------------------------
JbossCacheFacade - Attempt to retrieve a cache entry using key <28400024|28399250> and cache model <org.springmodules.cache.provider.jboss.JbossCacheCachingModel@4aa0ce[nodeFqn='jboss.cache:service=TreeCache']>
JbossCacheFacade - Retrieved cache element <null>
MethodMapFlushingInterceptor - Unable to flush cache. No model is associated to the intercepted method
JbossCacheFacade - Attempt to store the object <[Clark Li, Grant Ling]> in the cache using key <28400024|28399250> and model <org.springmodules.cache.provider.jboss.JbossCacheCachingModel@4aa0ce[nodeFqn='jboss.cache:service=TreeCache']>
JbossCacheFacade - Object was successfully stored in the cache
[Clark Li, Grant Ling]

      四、jar包清单

log4j-1.2.14.jar
spring.jar
spring-modules-cache.jar
commons-collections.jar
commons-logging.jar
jakarta-oro.jar
jboss-cache.jar
jboss-jmx.jar
jboss-system.jar
jgroups.jar
jboss-common.jar
jta.jar
concurrent.jar

       五、附另一JBoss Cache配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!-- ===================================================================== -->
<!-- -->
<!-- Sample JBoss Cache Service Configuration -->
<!-- -->
<!-- ===================================================================== -->
<server>
 <mbean code="org.jboss.cache.jmx.CacheJmxWrapper"
  name="jboss.cache:service=Cache">
  <!-- Configure the TransactionManager
  <attribute name="TransactionManagerLookupClass">
   org.jboss.cache.transaction.GenericTransactionManagerLookup
  </attribute>
  -->
  <!-- Node locking level : SERIALIZABLE
   REPEATABLE_READ (default)
   READ_COMMITTED
   READ_UNCOMMITTED
   NONE -->
  <attribute name="IsolationLevel">READ_COMMITTED</attribute>
  <!-- Lock parent before doing node additions/removes -->
  <attribute name="LockParentForChildInsertRemove">
   true
  </attribute>
  <!-- Valid modes are LOCAL (default)
   REPL_ASYNC
   REPL_SYNC
   INVALIDATION_ASYNC
   INVALIDATION_SYNC -->
  <attribute name="CacheMode">LOCAL</attribute>
  <!-- Max number of milliseconds to wait for a lock acquisition -->
  <attribute name="LockAcquisitionTimeout">15000</attribute>
  <!-- Specific eviction policy configurations. This is LRU -->
  <attribute name="EvictionConfig">
   <config>
    <attribute name="wakeUpIntervalSeconds">5</attribute>
    <attribute name="policyClass">
     org.jboss.cache.eviction.LRUPolicy
    </attribute>
    <!-- Cache wide default -->
    <region name="default">
     <attribute name="maxNodes">5000</attribute>
     <attribute name="timeToLiveSeconds">1000</attribute>
    </region>
   </config>
  </attribute>
 </mbean>
</server>

       六、参考文献

1、http://dev2dev.bea.com.cn/techdoc/20060718846.html

2、https://springmodules.dev.java.net/docs/reference/0.8/html_single/#cache-uses

3、springmodules下载地址:https://springmodules.dev.java.net/servlets/ProjectDocumentList?folderID=7051&expandFolder=7051&folderID=0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值