Spring实战之Cache

本文介绍如何在Spring框架中集成Ehcache进行缓存管理。通过配置Maven依赖、ehcache.xml及Spring配置文件,实现了对UserService的缓存代理,确保数据一致性的同时提升系统性能。

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


这里假定我们已经有了一些现成的类和接口,比如说

1> 一个现成的User POJO对象

2> 一个UserDao接口和UserDaoHibernateImpl实现类

3> 一个UserService接口和UserServiceImpl实现类

1. 这是使用的是Maven做的项目管理工具,在使用cache(这里使用的是ehcache)之前,需要引入以下依赖

  1. <dependency>
  2. <groupId>org.slf4j</groupId>
  3. <artifactId>slf4j-api</artifactId>
  4. <version>1.5.8</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.slf4j</groupId>
  8. <artifactId>slf4j-jdk14</artifactId>
  9. <version>1.5.8</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>net.sf.ehcache</groupId>
  13. <artifactId>ehcache</artifactId>
  14. <version>2.2.0</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.springmodules</groupId>
  18. <artifactId>spring-modules-cache</artifactId>
  19. <version>0.8</version>
  20. </dependency>

2.ehcache配置文件ehcache.xml

  1. <ehcache>
  2. <defaultCache
  3. maxElementsInMemory="500"
  4. eternal="true"
  5. overflowToDisk="false"
  6. memoryStoreEvictionPolicy="LFU"/>
  7. <cachename="userCache"
  8. maxElementsInMemory="500"
  9. eternal="true"
  10. overflowToDisk="false"
  11. memoryStoreEvictionPolicy="LFU"/>
  12. </ehcache>

3. spring配置文件

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <beansxmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xmlns:tx="http://www.springframework.org/schema/tx"
  6. xmlns:ehcache="http://www.springmodules.org/schema/ehcache"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsd
  8. http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-2.0.xsd
  9. http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.0.xsd
  10. http://www.springmodules.org/schema/ehcachehttp://www.springmodules.org/schema/cache/springmodules-ehcache.xsd"
  11. default-lazy-init="true">
  12. <ehcache:configconfigLocation="classpath:test/ehcache.xml"/>
  13. <ehcache:proxyid="cachedUserService"refId="userService">
  14. <ehcache:cachingmethodName="find*"cacheName="userCache"/>
  15. <ehcache:cachingmethodName="list*"cacheName="userCache"/>
  16. <ehcache:flushingmethodName="add*"cacheNames="userCache"when="before"/>
  17. <ehcache:flushingmethodName="update*"cacheNames="userCache"when="before"/>
  18. <ehcache:flushingmethodName="delete*"cacheNames="userCache"when="before"/>
  19. </ehcache:proxy>
  20. <beanid="userService"class="test.service.UserServiceImpl">
  21. <propertyname="userDao"ref="userDao"/>
  22. </bean>
  23. <beanid="userDao"class="test.dao.UserDaoHibernateImpl">
  24. <propertyname="sessionFactory"ref="mySessionFactory"/>
  25. </bean>
  26. <tx:adviceid="txAdvice"transaction-manager="myTransactionManager">
  27. <tx:attributes>
  28. <tx:methodname="get*"propagation="SUPPORTS"read-only="true"/>
  29. <tx:methodname="list*"propagation="SUPPORTS"read-only="true"/>
  30. <tx:methodname="find*"propagation="SUPPORTS"read-only="true"/>
  31. <tx:methodname="*"propagation="REQUIRED"/>
  32. </tx:attributes>
  33. </tx:advice>
  34. <aop:config>
  35. <aop:pointcutid="userServiceOperation"expression="execution(**..service.UserService.*(..))"/>
  36. <aop:advisoradvice-ref="txAdvice"pointcut-ref="userServiceOperation"/>
  37. </aop:config>
  38. <beanid="myTransactionManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  39. <propertyname="sessionFactory"ref="mySessionFactory"/>
  40. </bean>
  41. <beanid="mySessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  42. <propertyname="dataSource"ref="myDataSource"/>
  43. <propertyname="mappingResources">
  44. <list>
  45. <value>test/user.hbm.xml</value>
  46. </list>
  47. </property>
  48. <propertyname="hibernateProperties">
  49. <value>hibernate.dialect=org.hibernate.dialect.HSQLDialect</value>
  50. </property>
  51. </bean>
  52. <beanid="myDataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close">
  53. <propertyname="driverClassName"value="org.hsqldb.jdbcDriver"/>
  54. <propertyname="url"value="jdbc:hsqldb:res:hsqldb/testdb"/>
  55. <propertyname="username"value="sa"/>
  56. <propertyname="password"value=""/>
  57. </bean>
  58. </beans>

这里有几个地方需要注意:

1> 命名空间ehcache

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

http://www.springmodules.org/schema/ehcache http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd

2> 以下ehcache的配置项必须放在第一行,否则会抛出异常Unexpected exception parsing XML document from class path resource [org/garbagecan/springstudy/dao/hibernate/spring-cache.xml]; nested exception is java.lang.IllegalStateException: An implementation of CacheProviderFacade should be registered under the name 'cacheProvider'

  1. <ehcache:configconfigLocation="classpath:test/ehcache.xml"/>

3> 添加了一个cachedUserService bean,直接引用真实的service bean,这里为了测试的方便,所以没有使用使用内嵌bean的定义

  1. <ehcache:proxyid="cachedUserService"refId="userService">
  2. <ehcache:cachingmethodName="find*"cacheName="userCache"/>
  3. <ehcache:cachingmethodName="list*"cacheName="userCache"/>
  4. <ehcache:flushingmethodName="add*"cacheNames="userCache"when="before"/>
  5. <ehcache:flushingmethodName="update*"cacheNames="userCache"when="before"/>
  6. <ehcache:flushingmethodName="delete*"cacheNames="userCache"when="before"/>
  7. </ehcache:proxy>

4. 测试Test类

  1. packagetest;
  2. importjava.util.List;
  3. importorg.garbagecan.springstudy.dao.hibernate.service.UserService;
  4. importorg.springframework.context.ApplicationContext;
  5. importorg.springframework.context.support.ClassPathXmlApplicationContext;
  6. publicclassTest{
  7. publicstaticvoidmain(String[]args)throwsException{
  8. ApplicationContextctx=newClassPathXmlApplicationContext(
  9. "/test/spring-cache.xml");
  10. UserServiceuserService=(UserService)ctx.getBean("userService");
  11. UserServicecachedUserService=(UserService)ctx.getBean("cachedUserService");
  12. for(inti=0;i<10;i++){
  13. Useruser=newUser();
  14. user.setId(""+System.currentTimeMillis()+i);
  15. user.setName("name_"+System.currentTimeMillis()+i);
  16. user.setPassword("password_"+i);
  17. cachedUserService.add(user);
  18. }
  19. System.out.println(cachedUserService.list());
  20. List<User>users=userService.list();
  21. for(Useruser:users){
  22. user.setPassword("123456");
  23. userService.update(user);
  24. }
  25. System.out.println(cachedUserService.list());
  26. for(Useruser:users){
  27. user.setPassword("123456");
  28. cachedUserService.update(user);
  29. }
  30. System.out.println(cachedUserService.list());
  31. }
  32. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值