在任何读取繁重的数据库应用程序中,缓存仍然是最基本的性能增强机制之一。 Spring 3.1发行版提供了一个很酷的新功能,称为Cache Abstraction 。 Spring Cache Abstraction为应用程序开发人员提供了一种简单,透明和分离的方式来实现任何缓存解决方案。 Memcached是跨应用程序使用的最受欢迎的分布式缓存系统之一。 在本文中,我们将重点介绍如何将Memcached与启用Spring的应用程序集成。 由于Spring仅直接支持Ehcache和ConcurrentHashMap,因此我们将使用第三方库Simple Spring Memcache来利用Spring缓存抽象的功能。
获取代码
可以从以下SVN位置下载本教程的代码。 https://www.assembla.com/code/weblog4j/subversion/nodes/24/SpringDemos/trunk为了使本教程正常工作,请在您的数据库中创建下表。 然后在springcache.xml中修改数据源。
CREATE TABLE IF NOT EXISTS `adconnect`.`books` (`book_id` INT NOT NULL AUTO_INCREMENT ,`book_name` VARCHAR(500) NULL ,`book_author` VARCHAR(500) NULL ,`category` VARCHAR(500) NULL ,`numpages` INT NULL ,`price` FLOAT NULL ,PRIMARY KEY (`book_id`) )
ENGINE = InnoDB;
整合步骤
1. 依赖关系–我还假设您已经设置了休眠,弹簧和日志。 因此,要下载SSM依赖项,请在POM中添加以下内容。 有关全套依赖项,请从上面的SVN网址下载该项目。
<dependency><groupId>com.google.code.simple-spring-memcached</groupId><artifactId>spring-cache</artifactId><version>3.1.0</version>
</dependency><dependency><groupId>com.google.code.simple-spring-memcached</groupId><artifactId>xmemcached-provider</artifactId><version>3.1.0</version>
</dependency>
2. 启用缓存 –要在您的spring应用程序中启用缓存,请在spring上下文xml中添加以下内容。
<cache:annotation-driven/>
3. 配置Spring以启用基于Memcached的缓存 –在应用程序上下文xml中添加以下内容。
<bean name="cacheManager" class="com.google.code.ssm.spring.SSMCacheManager"><property name="caches"><set><bean class="com.google.code.ssm.spring.SSMCache"><constructor-arg name="cache" index="0" ref="defaultCache"/><!-- 5 minutes --><constructor-arg name="expiration" index="1" value="300"/><!-- @CacheEvict(..., "allEntries" = true) doesn't work --><constructor-arg name="allowClear" index="2" value="false"/></bean></set></property></bean><bean name="defaultCache" class="com.google.code.ssm.CacheFactory"><property name="cacheName" value="defaultCache"/><property name="cacheClientFactory"><bean name="cacheClientFactory" class="com.google.code.ssm.providers.xmemcached.MemcacheClientFactoryImpl"/></property><property name="addressProvider"><bean class="com.google.code.ssm.config.DefaultAddressProvider"><property name="address" value="127.0.0.1:11211"/></bean></property><property name="configuration"><bean class="com.google.code.ssm.providers.CacheConfiguration"><property name="consistentHashing" value="true"/></bean></property></bean>
SSMCacheManager扩展了org.springframework.cache.support.AbstractCacheManager –它是一个抽象类,并且是基础缓存的管理器。
SSMCache实现org.springframework.cache.Cache –这是底层缓存客户端api的实际包装器回合。
4. 注释驱动缓存 – Spring使用注释来标记要由缓存管理的方法。 这些是Spring缓存框架定义的注释
- @Cacheable –此批注用于标记要缓存其结果的方法。 如果调用了可缓存的方法,那么spring首先查看该方法的结果是否被缓存。 如果它存在于缓存中,则将结果从那里拉出,然后进行方法调用。
- @CachePut –标有cacheput批注的方法始终运行,并将其结果推送到缓存。 您不应将Cacheput和Cacheable批注放在相同的方法上,因为它们的行为不同。 Cacheput将导致方法始终执行,而可缓存的结果将导致方法仅执行一次。
- @CacheEvict –此注释导致从缓存中逐出对象。 通常在更新结果对象时使用此方法,因此需要清除缓存中的旧对象。
- @Caching –如果要在一个方法上放置多个相同类型的注释,则使用此注释。
@Cacheable演示
@Cacheable(value = "defaultCache", key = "new Integer(#book_id).toString().concat('.BookVO')")public BookVO get(int book_id) throws Exception {BookVO bookVO = null;try{Query query = getSession().createQuery("from BookVO bookVO where bookVO.book_id=:book_id");query.setLong("book_id", book_id);bookVO = (BookVO)query.uniqueResult();}catch(HibernateException he){log.error("Error in finding a bookVO : " + he);throw new Exception("Error in finding adPicVO by book_id for book_id : " + bookVO, he);}return bookVO;}
请注意注释的键属性。 这是Spring Expression Language的示例。 您可以根据需要使用SePL use创建memcache密钥。 在此示例中,我想要一个键,其格式应为<book_id> .BookVO。
另一个示例–假设我要存储给定作者的bookVO列表,在这种情况下,我可以使用格式为<author_name> .BookVOList的唯一键,因此可以使用以下键
@Cacheable(value = "defaultCache", key = "#author.concat('.BookVOList')")public List<BookVO> getList(String author) throws Exception {
@CachePut演示
@CachePut(value = "defaultCache", key = "new Integer(#bookVO.book_id).toString().concat('.BookVO')")public BookVO create(BookVO bookVO) throws Exception {try{getSession().save(bookVO);getSession().flush();}catch(HibernateException he){log.error("Error in inserting bookVO : " + he);throw new Exception("Error in inserting bookVO", he);}return bookVO;}
插入数据时可以使用CachePut,插入后可以将插入的数据放入缓存中
@CacheEvict演示
@CacheEvict(value = "defaultCache", key = "new Integer(#bookVO.book_id).toString().concat('.BookVO')")public BookVO update(BookVO bookVO) throws Exception {try{Query query = getSession().createQuery("update BookVO bookVO set bookVO.book_name=:book_name, bookVO.book_author=:book_author,bookVO.category=:category,bookVO.numpages=:numpages,bookVO.price=:price " +"where bookVO.book_id=:book_id");query.setString("book_name", bookVO.getBook_name());query.setString("book_author", bookVO.getBook_author());query.setString("category", bookVO.getCategory());query.setInteger("numpages", bookVO.getNumpages());query.setFloat("price", bookVO.getPrice());query.setLong("book_id", bookVO.getBook_id());query.executeUpdate();}catch(HibernateException he){log.error("Error in updating bookVO : " + he);throw new Exception("Error in updating bookVO", he);}return bookVO;}
资源资源
- https://code.google.com/p/simple-spring-memcached/
- http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/cache.html
- http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/expressions.html
- http://static.springsource.org/spring/docs/3.1.0.M1/javadoc-api/index.html?org/springframework/cache/CacheManager.html
- http://doanduyhai.wordpress.com/2012/07/01/cache-abstraction-in-spring-3/
- http://viralpatel.net/blogs/cache-support-spring-3-1-m1/
翻译自: https://www.javacodegeeks.com/2013/06/simple-spring-memcached-spring-caching-abstraction-and-memcached.html