自定义key说明
- “#” 井号可动态获取传入的参数的值,即可缓存不同的 key
//使用keyId 作为key
//字符串需要单引号 如代码 "'keyId'"
@Cacheable(value = "users", key = "'keyId'")
public User find(Integer id) {
returnnull;
}
//使用参数id值作为key
@Cacheable(value = "users", key = "#id")
public User find(Integer id) {
returnnull;
}
//使用函数第一个参数作为缓存的key
@Cacheable(value = "users", key = "#p0")
public User find(Integer id, String str) {
returnnull;
}
//使用user.id 的value为key
@Cacheable(value = "users", key = "#user.id")
public User find(User user) {
returnnull;
}
//使用第一个参数的id值作为key
@Cacheable(value = "users", key = "#p0.id")
public User find(User user) {
returnnull;
}
// 如果要用固定字符串加上参数的属性记得加单引号
@Cacheable(value = "users", key = "'helloworld'+#p0.id")
public User find(User user) {
returnnull;
}
@Cacheable(value = {"user1", "user2"}, key = "caches[0].name")
public User find(User user) {
returnnull;
}
缓存注解的使用
@Cacheable
Spring 在执行 @Cacheable 标注的方法前先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,执行该方法并将方法返回值放进缓存。
参数: value缓存名、 key缓存键值、 condition满足缓存条件、unless否决缓存条件
@CachePut
和 @Cacheable 类似,但会把方法的返回值放入缓存中, 主要用于数据新增和修改方法
@CacheEvict
方法执行成功后会从缓存中移除相应数据。
参数: value缓存名、 key缓存键值、 condition满足缓存条件、 unless否决缓存条件、 allEntries是否移除所有数据(设置为true时会移除所有缓存)
小结
- @Cacheable,@CachePut , @CacheEvict都有value属性,指定的是要使用缓存名称;key属性指定的是数据在缓存中的存储的键。
- @Cacheable(“users”);这个相当于 save() 操作,
- @cachePut相当于 Update() 操作,只要他标示的方法被调用,那么都会缓存起来,而@Cacheable则是先看下有没已经缓存了,然后再选择是否执行方法。
- @CacheEvict相当于Delete()操作。用来清除缓存用的