在Spring中快速使用EHCache注解

来源:互联网 发布:网络美女排行榜2013 编辑:程序博客网 时间:2024/05/10 03:22
 作为一名Java开发人员你一定想知道如何在Spring应用中使用新的Ehcache注解功能;是吧?ehcache-spring-annotatios是获得Apache认证的一个开源项目;它大大简化了在Spring应用中基于业界使用广泛的Ehacche-2.0版本实现缓存的技术,1.1.2版本的ehcache-spring-annotations刚刚发布不久,在本文中,我将会介绍如何在一个web工程时使用ehcache-spring-annotations实现缓存机制。

 

创建一个Web工程

        在本例中,我们将会创建一个基于Spring MVC的web工程,如果您使用的IDE是Eclipse的话请确保您安装了m2eclipse插件(译者注:因为我们的工程基于Maven构建);接着创建一个基于JAVA EE 5 Web应用模型的Maven工程(group id:org.codehaus.mojo.archetypes,artifact id: webapp-jee5)。

http://blog.goyello.com/wp-content/uploads/2010/07/wtp.png

上述示例在Eclipse3.6下可以很好的运行。

工程结构

首先我创建了一个简单的web工程,项目中包含一个控制器:MessageController:

[c-sharp] view plaincopyprint?
  1. @Controller  
  2. public class MessageController {  
  3.      @Autowired(required = true)  
  4.      private MessageStorage messageStorage;  
  5.      public MessageController(MessageStorage messageStorage) {  
  6.           super();  
  7.           this.messageStorage = messageStorage;  
  8.      }  
  9.      public MessageController() {  
  10.      }  
  11.      @RequestMapping(method = RequestMethod.GET, value = "/message/add")  
  12.      public ModelAndView messageForm() {  
  13.          return new ModelAndView("message-form", "command", new Message());  
  14.      }  
  15.      @RequestMapping(method = RequestMethod.POST, value = "/message/add")  
  16.      public ModelAndView addMessage(@ModelAttribute Message message) {  
  17.           messageStorage.addMessage(message);  
  18.           return getMessageById(message.getId());  
  19.      }  
  20.      @RequestMapping(method = RequestMethod.GET, value = "/message/{id}")  
  21.      public ModelAndView getMessageById(@PathVariable("id") long id) {  
  22.          Message message = messageStorage.findMessage(id);  
  23.          ModelAndView mav = new ModelAndView("message-details");  
  24.          mav.addObject("message", message);  
  25.          return mav;  
  26.      }  
  27.      @RequestMapping(method = RequestMethod.GET, value = "/message")  
  28.      public ModelAndView getAllMessages() {  
  29.      Collection<Message> messages = messageStorage.findAllMessages();  
  30.          ModelAndView mav = new ModelAndView("messages");  
  31.          mav.addObject("messages", new CollectionOfElements(messages));  
  32.          return mav;  
  33.      }  
  34. }  

上面的控制器依赖于一个简单的DAO对象:MessageStorage,其实现如下:

 

[java] view plaincopyprint?
  1. public interface MessageStorage {  
  2.     Message findMessage(long id);  
  3.     Collection<Message> findAllMessages();  
  4.     void addMessage(Message message);  
  5.     void setDelegate(MessageStorage storageDelegate);  
  6. }  

 

MessageStorage接口的唯一实现类是MemoryMessageStorage:

[c-sharp] view plaincopyprint?
  1. @Component  
  2. public class MemoryMessageStorage implements MessageStorage {  
  3.       
  4.     private Map<Long, Message> messages;  
  5.     private AtomicLong newID;  
  6.       
  7.     @PostConstruct  
  8.     public void initialize() {  
  9.         // add some messages  
  10.         addMessage(new Message("user:1", "content-1"));  
  11.         addMessage(new Message("user:2", "content-2"));  
  12.         addMessage(new Message("user:3", "content-3"));  
  13.         addMessage(new Message("user:4", "content-4"));  
  14.         addMessage(new Message("user:5", "content-5"));  
  15.     }  
  16.       
  17.     @Override  
  18.     @Cacheable(cacheName = "messageCache")  
  19.     public Message findMessage(long id) {  
  20.         //...  
  21.     }  
  22.     @Override  
  23.     @Cacheable(cacheName = "messagesCache")  
  24.     public Collection<Message> findAllMessages() {  
  25.         //...  
  26.     }  
  27.     @Override  
  28.     @TriggersRemove(cacheName = "messagesCache", when = When.AFTER_METHOD_INVOCATION, removeAll = true)  
  29.     public void addMessage(Message message) {  
  30.         //...  
  31.     }  
  32. }  
 

通过如下的所展示的必须的依赖配置之后我们就可以运行这个应用程序了(见下载选项获取完整的应用程序代码)

 

[xhtml] view plaincopyprint?
  1. <dependencies>  
  2.         <dependency>  
  3.             <groupId>javax.servlet</groupId>  
  4.             <artifactId>servlet-api</artifactId>  
  5.             <version>2.5</version>  
  6.             <scope>provided</scope>  
  7.         </dependency>  
  8.         <dependency>  
  9.             <groupId>javax.servlet.jsp</groupId>  
  10.             <artifactId>jsp-api</artifactId>  
  11.             <version>2.1</version>  
  12.             <scope>provided</scope>  
  13.         </dependency>  
  14.         <dependency>  
  15.             <groupId>junit</groupId>  
  16.             <artifactId>junit</artifactId>  
  17.             <version>4.8.1</version>  
  18.             <scope>test</scope>  
  19.         </dependency>  
  20.         <dependency>  
  21.             <groupId>org.springframework</groupId>  
  22.             <artifactId>spring-webmvc</artifactId>  
  23.             <version>3.0.3.RELEASE</version>  
  24.             <type>jar</type>  
  25.             <scope>compile</scope>  
  26.         </dependency>  
  27.         <dependency>  
  28.             <groupId>org.springframework</groupId>  
  29.             <artifactId>spring-oxm</artifactId>  
  30.             <version>3.0.3.RELEASE</version>  
  31.             <type>jar</type>  
  32.             <scope>compile</scope>  
  33.         </dependency>  
  34.         <dependency>  
  35.             <groupId>javax.servlet</groupId>  
  36.             <artifactId>jstl</artifactId>  
  37.             <version>1.2</version>  
  38.             <type>jar</type>  
  39.             <scope>compile</scope>  
  40.         </dependency>  
  41.     </dependencies>  
 

介绍基于Spring的web工程中使用Ehcache注解

现在该给项目增加缓存能力了,我们要为MemoryMessageStorage类提供缓存机制。首先,在POM文件中加入所需的依赖:

Spring中Ehcache的注解依赖项:

[xhtml] view plaincopyprint?
  1. <dependency>  
  2.     <groupId>com.googlecode.ehcache-spring-annotations</groupId>  
  3.     <artifactId>ehcache-spring-annotations</artifactId>  
  4.     <version>1.1.2</version>  
  5.     <type>jar</type>  
  6.     <scope>compile</scope>  
  7. </dependency>  
 

在写本文的时候2.2.0版本的Ehcache也可用了,但是我们使用2.1.0版本的Ehcache,因为Ehcache Annotations for Spring 1.1.2版本是基于2.1.0版本的Ehcache的。

我还填加了SLF4J API实现的依赖(译者注:SLF4J不是具体的日志解决方案,它只服务于各种各样的日志系统。按照官方的说法,SLF4J是一个用于日志系统的简单Facade,允许最终用户在部署其应用时使用其所希望的日志系统。):

[xhtml] view plaincopyprint?
  1. <dependency>  
  2.      <groupId>org.slf4j</groupId>  
  3.      <artifactId>slf4j-log4j12</artifactId>  
  4.      <version>1.6.1</version>  
  5.      <type>jar</type>  
  6.      <scope>compile</scope>  
  7. </dependency>  
 

通过上面依赖的配置,我们就可以使用Ehcache Annotations for Spring了,我们现在就如同前面所说的给MemoryMessageStorage添加注解。这里列出几条所需达到的目标:

 

·        当调用findMessage(long)方法时用名为“messageCache”的名称缓存结果信息。

·        当调用findAllMessages()方法时用名为“messagesCache”的名称缓存结果信息。

·        当调用addMessage(Message)方法时清除所有“messagesCache”名称下的缓存项。

为了达到上面所说的几个目标,我们使用 @Cachable和@TriggersRemove两个注解,见下面介绍:

[java] view plaincopyprint?
  1. @Component  
  2. public class MemoryMessageStorage implements MessageStorage {  
  3.     private Map<Long, Message> messages;  
  4.     private AtomicLong newID;  
  5.     public MemoryMessageStorage() {  
  6.         // ...  
  7.     }  
  8.     @Override  
  9.     @Cacheable(cacheName = "messageCache")  
  10.     public Message findMessage(long id) {  
  11.         // ...  
  12.     }  
  13.     @Override  
  14.     @Cacheable(cacheName = "messagesCache")  
  15.          public Collection<Message> findAllMessages() {  
  16.          // ...  
  17.     }  
  18.     @Override  
  19.     @TriggersRemove(cacheName = "messagesCache", when = When.AFTER_METHOD_INVOCATION, removeAll = true)  
  20.         public void addMessage(Message message) {  
  21.             // ...  
  22.     }  
  23. }  
 

Spring和Ehcache的配置

注解已经加到位了,接下来我们需要配置这个项目去使它们起作用,通过Spring的配置文件就可以达到这个目的:

[xhtml] view plaincopyprint?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.        xmlns:oxm="http://www.springframework.org/schema/oxm"  
  6.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  7.        xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"  
  8.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  9.        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  10.        http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd  
  11.        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
  12.         http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">  
  13.     <ehcache:annotation-driven />  
  14.     <ehcache:config cache-manager="cacheManager">  
  15.         <ehcache:evict-expired-elements interval="60" />  
  16.     </ehcache:config>  
  17.     <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/>  
  18.     <!-- rest of the file omitted -->  
  19. </beans>  

最后要做的是添加Ehcache的配置文件,在web应用程序的/WEB-INF目录下面创建ehcache.xml的xml文件:

[xhtml] view plaincopyprint?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">  
  3.     <defaultCache eternal="true" maxElementsInMemory="100" overflowToDisk="false" />  
  4.     <cache name="messageCache" maxElementsInMemory="10" eternal="true" overflowToDisk="false" />  
  5.     <cache name="messagesCache" maxElementsInMemory="10" eternal="true" overflowToDisk="false" />  
  6. </ehcache>  
 

接下来需要配置缓存manager使它去管理Ehcache的配置,在Spring上下文的配置文件中加入cacheManager 这个Bean的配置,并需要在其中加入configLocation属性:

[xhtml] view plaincopyprint?
  1. <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">  
  2.      <property name="configLocation"  value="/WEB-INF/ehcache.xml"/>  
  3. </bean>  
 

配置完毕,在Tomcat 6应用服务器上运行该应用程序(Run As – Run on server),你会发现有日志输出-如果DEBUG模式被允许的话你会发现类似如下的条目输出:

[java] view plaincopyprint?
  1. DEBUG [net.sf.ehcache.Cache]: Initialised cache: messagesCache  
  2. DEBUG [net.sf.ehcache.Cache]: Initialised cache: messageCache  
 

在项目中做一些调试去观察缓存机制的行为(确保DEBUG日志级别是被允许的)。方法是(去看XML的输出,将“html”替换为“xml”):

获取消息列表 –http://localhost:8080/esa/message.html

通过ID获取消息 –http://localhost:8080/esa/message/{id}.html

 添加一条信息(from) –http://localhost:8080/esa/message/add.html

如果您是第一次执行MessageController 类的getMessages()方法,您将会看到:

[java] view plaincopyprint?
  1. DEBUG [com.googlecode.ehcache.annotations.interceptor.EhCacheInterceptor]: Generated key '167334053963' for invocation: ReflectiveMethodInvocation: public abstract java.util.Collection com.goyello.esa.storage.MessageStorage.findAllMessages(); target is of class [com.goyello.esa.storage.MemoryMessageStorage]  
  2. DEBUG [com.goyello.esa.storage.MemoryMessageStorage]: == got all messages, size=5  
 

当第二次调用同一个方法时,上面输出的日志的第二行就不会再出现,因为所有收集的信息都是从Cache中检索出来的。

调用MessageController中的addMessage()方法时清除Cache中的信息很简单,重复上面的步骤,确保cache在之前是被清空的。

单元测试

为了确保缓存机制确实起作用了,而不是只是看到日志,我们创建单元测试去进行测试。为进行这个测试我们修改了MessageStorage接口,我们在其中增加了void setDelegate(MessageStoragestorageDelegate)方法;给出的示例是为了检测我们添加的缓存机制确实起作用了;实现类的变化如下(其他所有方法类似):

[java] view plaincopyprint?
  1. @Override  
  2. @Cacheable(cacheName = "messageCache")  
  3. public Message findMessage(long id) {  
  4.          LOG.debug("== find message by id={}", id);  
  5.          if(storageDelegate != null)  
  6.          storageDelegate.findMessage(id);  
  7.          return messages.get(id);  
  8. }  
 

为了使测试简单一些我们需要使用了两个依赖:Spring Test 和Mockito:

 

[c-sharp] view plaincopyprint?
  1. <dependency>  
  2.             <groupId>org.mockito</groupId>  
  3.             <artifactId>mockito-all</artifactId>  
  4.             <version>1.8.5</version>  
  5.             <type>jar</type>  
  6.             <scope>compile</scope>  
  7. </dependency>  
  8. <dependency>  
  9.             <groupId>org.springframework</groupId>  
  10.             <artifactId>spring-test</artifactId>  
  11.             <version>3.0.3.RELEASE</version>  
  12.             <type>jar</type>  
  13.             <scope>compile</scope>  
  14. </dependency>  
 

测试类将依托于SpringJUnit4ClassRunner运行:

[c-sharp] view plaincopyprint?
  1. @RunWith(SpringJUnit4ClassRunner.class)  
  2. @ContextConfiguration(locations = { "/spring-context-test.xml" })  
  3. public class CachingTest {  
  4.      @Autowired  
  5.      ApplicationContext context;  
  6.      @Autowired  
  7.      CacheManager cacheManager;  
  8.      MessageStorage storage;  
  9.      MessageStorage storageDelegate;  
  10.      MessageController controller;  
  11.      @Before  
  12.      public void before() throws Exception {  
  13.          storageDelegate = Mockito.mock(MessageStorage.class);  
  14.          storage = (MessageStorage) context.getBean("messageStorage");  
  15.          storage.setDelegate(storageDelegate);  
  16.          controller = new MessageController(storage);  
  17.          cacheManager.clearAll();  
  18.      }  
  19.      @Test  
  20.      public void testCaching_MessagesCache() {  
  21.          controller.getAllMessages();  
  22.          controller.getAllMessages();  
  23.          verify(storageDelegate, times(1)).findAllMessages();  
  24.      }  
  25.      @Test  
  26.      public void testCaching_MessagesCacheRemove() {  
  27.          controller.getAllMessages();  
  28.          controller.getAllMessages();  
  29.          controller.addMessage(new Message());  
  30.          controller.getAllMessages();  
  31.          verify(storageDelegate, times(2)).findAllMessages();  
  32.          verify(storageDelegate, times(1)).addMessage(any(Message.class));  
  33.      }  
  34.      @Test  
  35.      public void testCaching_MessageCache() {  
  36.          controller.getMessageById(1);  
  37.          controller.getMessageById(1);  
  38.          controller.addMessage(new Message());  
  39.          controller.getMessageById(1);  
  40.          verify(storageDelegate, times(1)).findMessage(1);  
  41.          verify(storageDelegate, times(1)).addMessage(any(Message.class));  
  42.      }  
  43. }  
 

本示例是一个模拟的对象用于测试实际的MessageStorage上的调用次数。本测试Spring上下文的配置如下:

[xhtml] view plaincopyprint?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xmlns:context="http://www.springframework.org/schema/context" xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  5.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  6.         http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd">  
  7.     <ehcache:annotation-driven />  
  8.     <ehcache:config cache-manager="cacheManager">  
  9.         <ehcache:evict-expired-elements interval="60" />  
  10.     </ehcache:config>  
  11.     <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">  
  12.         <property name="configLocation" value="classpath:ehcache-test.xml" />  
  13.     </bean>  
  14.     <bean id="messageStorage" class="com.goyello.esa.storage.MemoryMessageStorage" />  
  15. </beans>  
 

现在我们准备运行创建好的测试用例去验证实际在MemoryMessageStorage上的调用。我们期待的结果是:
http://blog.goyello.com/wp-content/uploads/2010/07/test.png

总结

使用Ehcache Spring Annotations是很简洁的,通过上述简单的一些步骤我们试图介绍如何在您的应用中使用缓存,我强烈建议您在您的项目中使用本工具之前先去我们的网站上去读一下文档,这样您会了解一些这篇文章没有覆盖到的用法。

参考文献

Ehcache Spring Annotations项目主页– http://code.google.com/p/ehcache-spring-annotations/

Ehcache项目首页– http://ehcache.org/

Spring 3.0参考– http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/
Mockito – http://mockito.org/
Maven2 – http://maven.apache.org/

下载并运行项目

完整的工程代码在这儿可以下载到:demo-project

下载了文件之后,解压缩,进入到工程所在的目录并执行下面的命令(需要安装maven2)

mvn clean tomcat:run

启动您的浏览器去看看应用的执行情况:

http://localhost:8080/esa/message.html

http://localhost:8080/esa/message/add.html

原创粉丝点击