spEL(Spring Expression Language) 定义缓存key 和各种 condition 。
spring Cache 利用AOP代理结束来实现
spring 提供了 CacheManage ,可以配置redis 缓存。
| 注解 | 作用 | 参数说明 |
|---|---|---|
| @Cacheable | 对方法配置,对方法结果缓存 | value: 缓存名 在spring配置文件中定义 key: 缓存的key ,可以为空或指定SpEL。默认按照方法所有参数进行组合 condition: 缓存条件,可以为空。SpEL 编写返回 true、fasle ,true时进行缓存 |
| @CachePut | 方法配置,调用方法后对结果缓存 | 参数同 @Cacheable 一样 |
| @CacheEvict | 方法配置,按条件删除缓存 | 参数痛@CAcheable 一样 allEntries: 是否清空所有缓存内容,默认fasle beforeInvocation: 是否在方法执行前就清空,默认 fasle (方法出异常不会清空) |
@Cacheable(value = "users" , key = "#user.userName" , condition = "#user.age < 35") User getUserList();
| 名称 | 位置 | 描述 | 例子 |
|---|---|---|---|
| methodName | root对象 | 当前被调用方法名 | #root.methodnaame |
| method | root对象 | 当前被调用方法 | #root.method.name |
| target | root对象 | 当前被调用的目标对象实例 | #root.target |
| targetClass | root对象 | 当前被调用的目标对象的类 | #root.targetClass |
| args | root对象 | 当前被调用方法的参数列表 | #root.args[0] |
| caches | root对象 | 当前方法调用使用的缓存列表 | #root.caches[0].name |
| Argument | 执行上下文 | 当前被调用的方法参数, method( User u ) 通过 #u.name 获取 | #u.name |
| result | 执行上下文 | 方法执行后返回值( 方法执行后判定有效 ) @CacheVict (beforeInvocation = false) | #result |
//接口上添加缓存
public interface CacheService {
@Cacheable(value = "userList" , key = "methodName")
List list();
@Cacheable(value = "user",key = "'user'.concat(#id.toString())")
User findUserById(Long id);
//这里只修改 3 号
//@CachePut(value="user",key="'user'.concat(#user.name.toString())")
@CachePut(value="user",key="'user'.concat(3)")
User update(User user);
@CacheEvict(value = "user", key = "'user'.concat(#id.toString())")
void remove(Long id);
}
底部


