spring cache使用

Spring 3.1 引入了基于注释(annotation)的缓存(cache)技术,它本质上不是一个具体的缓存实现方案(例如 EHCache 或者 OSCache),而是一个对缓存使用的抽象,经过在既有代码中添加少许它定义的各类 annotation,即可以达到缓存方法的返回对象的效果。redis

服务类中使用@Cacheable

@Service
public class UserService {
	
	@Cacheable(value= {"user-cache"},key="#id")
	public User getUserById(String id) {
		System.out.println("這次沒有使用緩存");
		User user = new User();
		user.setId("12345");
		user.setUserName("sean");
		user.setPassWord("password123");
		return user;
	}
}

@Cacheable(value= {"user-cache"},key="#id")这个注解的意思是当调用这个方法的时候,会从一个名叫 user-cache的缓存中查询key为id的值。若是不存在,则执行实际的方法并将结果写入缓存。若是存就从缓存中读取,在这里的缓存中的 key 就是参数 id。spring

因为本项目配置了redis做为缓存方案,数据将会被放入redis中存储。执行该方法以后redis中存储数据。出现user-cache缓存,keyid为12345缓存

 

@Cacheable注解使用app

value:指定一个或多个cache名称,同cacheNames。ide

key:存储对象的key。ui

除了使用方法参数(#参数名 或 #参数.属性名 )做为key,我还能够使用root对象来生成key。spa

1.spring 默认使用root对象属性,#root能够省略code

@Cacheable(value = { "sampleCache" ,"sampleCache2"},key="cache[1].name")

使用当前缓存“sampleCache2”的名称做为key。对象

2.自定义key:key = 类名.方法名.参数值  添加字符用单引号blog

@Cacheable(value = { "user-cache"},key="targetClass.getName()+'.'+methodName+'.'+#id")

使用当前被调用的class类名+被调用方法名+参数id拼接以后作key值。

 

3.除了使用key指定外,Spring还提供了org.springframework.cache.interceptor.KeyGenerator接口,使用keyGenerator去指定实现此接口的bean的名字。

@Cacheable(cacheNames="sampleCache", keyGenerator="myKeyGenerator")

4.condition : 指定发生条件

@Cacheable(condition="#id >5")  //参数id 大于5时加入缓存

cache配置类

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

	@Bean
	public KeyGenerator keyGenerator() {
		return new KeyGenerator() {

			@Override
			public Object generate(Object target, Method method, Object... params) {
				StringBuilder sb = new StringBuilder();
				sb.append(target.getClass().getName());
				sb.append(method.getName());
				for (Object object : params) {
					sb.append(object.toString());
				}

				return sb.toString();
			}
		};
	}
}

@EnableCaching注解是spring framework中的注解驱动的缓存管理功能。自spring版本3.1起加入了该注解。若是你使用了这个注解,那么你就不须要在XML文件中配置cache manager了,等价于 <cache:annotation-driven/> 。可以在服务类方法上标注@Cacheable。

使用keyGenerator设置key值

@Cacheable(value= {"login-user-cache"},keyGenerator="keyGenerator")
	public User getUserByName(String userName) {
		System.out.println("這次沒有使用緩存");
		User user = new User();
		user.setId("12346");
		user.setUserName("jiafeng");
		user.setPassWord("password123");
		return user;
		
	}

执行该方法以后缓存内容按照keyGenerator定义的规则生成key值。

相关文章
相关标签/搜索