Spring中@Cacheable的用法
在Spring中通过获取MemCachedClient来实现与memcached服务器进行数据读取的方式。不过,在实际开发中,我们往往是通过Spring的@Cacheable来实现数据的缓存的,所以,本文给大家详细介绍一下@Cacheable的用法。首先,在使用@Cacheable之前,我们要做好准备工作。
第一步:要导入相应的jar包。
<classpathentry kind="lib" path="lib/spring-core-4.1.4.RELEASE.jar"/>
<classpathentry kind="lib" path="lib/spring-cache-1.0.10.jar"/>
<classpathentry kind="lib" path="lib/spring-context-4.1.4.RELEASE.jar"/>
<classpathentry kind="lib" path="lib/spring-beans-4.1.4.RELEASE.jar"/>
<classpathentry kind="lib" path="lib/commons-logging-1.2.jar"/>
<classpathentry kind="lib" path="lib/log4j-1.2.17.jar"/>
<classpathentry kind="lib" path="lib/spring-expression-4.1.4.RELEASE.jar"/>
<classpathentry kind="lib" path="lib/java_memcached-release_2.0.1.jar"/>
<classpathentry kind="lib" path="lib/spring-aop-4.1.4.RELEASE.jar"/>
<classpathentry kind="lib" path="lib/spring-aspects-4.1.4.RELEASE.jar"/>
<classpathentry kind="lib" path="lib/spring-context-support-4.1.4.RELEASE.jar"/>
<classpathentry kind="lib" path="lib/spring-tx-4.1.4.RELEASE.jar"/>
<classpathentry kind="lib" path="lib/aopalliance-1.0.jar"/>
<classpathentry kind="lib" path="lib/ognl-3.0.6.jar"/>
<classpathentry kind="lib" path="lib/trafficCounter-1.0.2.jar"/>
<classpathentry kind="lib" path="lib/aspectjweaver-1.8.4.jar"/>
<classpathentry kind="lib" path="lib/javassist-3.11.0.GA.jar"/>
第二步:xml文件中增加命名空间。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
第三步:添加自动扫描功能。
<context:component-scan base-package="service" /> <aop:config proxy-target-class="true"/>
第四步:增加缓存管理类。
<bean id="memCacheProvider" class="com.springcache.memcache.MemCacheProvider">
<property name="memCache" ref="memCacheClient"/>
</bean>
<bean id="cacheManager" class="com.springcache.CacheManager">
<property name="elParserName" value="ognl"/>
<property name="cacheProviders">
<map>
<entry key="remote" value-ref="memCacheProvider"></entry>
</map>
</property>
</bean>
第五步:建立一个测试类。
package service;
import org.springframework.stereotype.Service;
import com.springcache.annotation.Cacheable;
@Service
@Cacheable
public class MemcachedService {
@Cacheable(name = "remote", key = "'USER_NAME_'+#args[0]", expire = 60 )
public String storeUserName(String accountId, String name)
{
return name;
}
@Cacheable(name = "remote", expire = 60)
public String storeUserAddress(String accountId, String address)
{
return address;
}
}
@Cacheable支持如下几个参数:
key:缓存的key,默认为空,既表示使用方法的参数类型及参数值作为key,支持SpEL。例如:memCachedService.storeUserAddress("user", "BeiJing");
所以对应的key为:service.MemcachedService-storeUserAddress_user_BeiJing
name:存储位置。在本来中remote表示使用memcached服务器。
condition:触发条件,只有满足条件的情况才会加入缓存,默认为空,既表示全部都加入缓存,支持SpEL。
expire:过期时间,单位为秒。
第六 扩展:使用Spring4.3解决缓存过期后多线程并发访问数据库的问题
缓存过期之后,如果多个线程同时请求对某个数据的访问,会同时去到数据库,导致数据库瞬间负荷增高。Spring4.3为@Cacheable注解提供了一个新的参数“sync”(boolean类型,缺省为false),
当设置它为true时,只有一个线程的请求会去到数据库,其他线程都会等待直到缓存可用。这个设置可以减少对数据库的瞬间并发访问。
不过不一定所有的缓存系统都支持这个配置。经过验证,Guava Cache是支持的 参考:http://blog.csdn.net/clementad/article/details/51250472
@Service
public class UserServiceCacheablesImpl implements UserServiceCacheables{
private final static Logger logger = LoggerFactory.getLogger(UserServiceCacheablesImpl.class);
@Autowired
UserDAO userDAO;
@Override
@Cacheable(value="getPhoneNoByUserId", sync=true)
public String getPhoneNoByUserId(int userId) {
logger.debug("getting data from database, userId={}", userId);
return userDAO.getPhoneNoByUserId(userId);
}
}
最后总结一下:当执行到一个被@Cacheable注解的方法时,Spring首先检查condition条件是否满足,如果不满足,执行方法,返回;如果满足,在name所命名的缓存空间中查找使用key存储的对象,如果找到,将找到的结果返回,如果没有找到执行方法,将方法的返回值以key-value对象的方式存入name缓存中,然后方法返回。
Spring中@Cacheable的用法的更多相关文章
- 框架源码系列十:Spring AOP(AOP的核心概念回顾、Spring中AOP的用法、Spring AOP 源码学习)
一.AOP的核心概念回顾 https://docs.spring.io/spring/docs/5.1.3.RELEASE/spring-framework-reference/core.html#a ...
- Spring中HibernateCallback的用法(转)
Hibernate的复杂用法HibernateCallback HibernateTemplate还提供一种更加灵活的方式来操作数据库,通过这种方式可以完全使用Hibernate的操作方式.Hiber ...
- Spring中jdbcTemplate的用法实例
一.首先配置JdbcTemplate: 要使用Jdbctemplate 对象来完成jdbc 操作.通常情况下,有三种种方式得到JdbcTemplate 对象. 第一种方式:我们可以在自己定 ...
- Spring 中classPath:用法
参考文章地址: http://hi.baidu.com/huahua035/item/ac8a27a994b55bad29ce9d39 http://blog.csdn.net/lushuaiyin/ ...
- spring 中StoredProcedure的用法--转载
StoredProcedure是一个抽象类,必须写一个子类来继承它,这个类是用来简化JDBCTemplate执行存储过程操作的. 首先我们写一个实现类: package com.huaye.frame ...
- Spring中ApplicationContextAware的用法
详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcyt379 一.这个接口有什么用? 当一个类实现了这个接口(Application ...
- Spring中RedirectAttributes的用法
RedirectAttributes 是Spring mvc 3.1版本之后出来的一个功能,专门用于重定向之后还能带参数跳转的的工具类.他有两种带参的方式: 第一种: redirectAttribut ...
- 简介spring中MethodReplacer的用法
欢迎转载交流:个人博客地址http://www.cnblogs.com/shizhongtao/p/3468713.html org.springframework.beans.factory.sup ...
- spring中ApplicationListener的用法
1.实现ApplicationListener接口,并重写onApplicationEvent方法 @Component public class RSAKeyInitListener impleme ...
随机推荐
- ios-通知简单示例
通知是一种一对多的信息广播机制,一个应用程序同时只能有一个NSNotificationCenter(通知中心)对象,用来添加通知观察者或者说监听者,以及发送通知. 用的地方是:不同控制器的传值回调.d ...
- ios-点击图片放大,背景变半透明
在view中点击一个图片,图片放大,背景变半透明,图片不会变透明的效果图如下 思路:图片框是一个按钮,监听点击事件. 当点击图片后:改变图片的frame,使图片放大,并且在controller.vie ...
- MVC 学习系列
总是很难说清MVC的概念,即使读了源代码后(读的时候有些东西,理解起来还是有点吃力),也依然能难对整体的每一个具体的原理说的一清二楚.为了达到自己学习的目的,我把自己的学习路线写成文章,一边自己能对M ...
- C++Primer 第十八章
//1.异常:待研究 //2.命名空间: // A:多个库将名字放置在全局命名空间中将引发命名空间污染. // B:命名空间为防止名字冲突提供了更加可控的机制.命名空间分割了全局命名空间,其中每个命名 ...
- SLF4简介
The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logg ...
- 转:Java实现几种常见排序方法
日常操作中常见的排序方法有:冒泡排序.快速排序.选择排序.插入排序.希尔排序,甚至还有基数排序.鸡尾酒排序.桶排序.鸽巢排序.归并排序等. 冒泡排序是一种简单的排序算法.它重复地走访过要排序的数列,一 ...
- C#: 获取当前应用程序所在路径
ref: http://www.cnblogs.com/netlyf/archive/2011/06/22/2086718.html 一.获取当前文件的路径 string str1=Process.G ...
- HDU 1724 Ellipse(数值积分の辛普森公式)
Problem Description Math is important!! Many students failed in 2+2’s mathematical test, so let's AC ...
- C语言 单引号 双引号问题
C语言中的单引号和双引号含义迥异,用单引号引起的一个字符实际上代表一个整数,整数值对应于该字符在编译器采用的字符集中的序列值,因此,采用ASCII字符集的编译器而言,‘a’的含义与0141或97严格一 ...
- Android中使用ShareSDK实现分享
1,在http://www.mob.com官网上去创建一个后台应用(如果没有账号的同学要去先注册一下),主要后去的是你新创建的应用的appKey值 2,这里我们分享新浪微博为例,在新浪微博的sdk中创 ...