redisson + CacheManager缓存管理
1 背景
系统缓存进行统一管理,结合Sping框架的CacheManager的接口,使用@Cacheable、@CacheEvit注解进行缓存管理
2 CacheManager相关功能类介绍
2.1 接口
2.1.1 CacheManager接口
CacheManager接口如下所示,主要方法getCache通过缓存name获取Cache接口
public interface CacheManager {
@Nullable
Cache getCache(String name);
Collection<String> getCacheNames();
}
2.1.2 Cache接口
Cache接口结构如下,主要方法是get和put,类似于Map的操作,不同的是get方法返回的是ValueWrapper,是一个值的包装接口,详情见1.3;
Cache内部主要接口还有evict方法(删除指定key)、invalidate和clear方法(删除整个Cache)、put方法(新增一个元素)、get方法(获取key对应的ValueWrapper接口)
public interface Cache {
String getName();
Object getNativeCache();
@Nullable
Cache.ValueWrapper get(Object key);
@Nullable
<T> T get(Object key, @Nullable Class<T> type);
@Nullable
<T> T get(Object key, Callable<T> valueLoader);
void put(Object key, @Nullable Object value);
@Nullable
default Cache.ValueWrapper putIfAbsent(Object key, @Nullable Object value) {
Cache.ValueWrapper existingValue = this.get(key);
if (existingValue == null) {
this.put(key, value);
}
return existingValue;
}
void evict(Object key);
default boolean evictIfPresent(Object key) {
this.evict(key);
return false;
}
void clear();
default boolean invalidate() {
this.clear();
return false;
}
@FunctionalInterface
public interface ValueWrapper {
@Nullable
Object get();
}
}
2.1.3 ValueWrapper接口
ValueWrapper接口是获取值的接口,结构如下;只有一个get方法,返回值是key对应的对象,不同的CacheManager实现类实现了不同的ValueWrapper,主要内容就是将存储的对象反序列化并返回
@FunctionalInterface
public interface ValueWrapper {
@Nullable
Object get();
}
2.2 注解
2.2.1 @Cacheable注解
使用在方法上,用于方法结果的缓存;每次先查询缓存查询到结果直接返回,查询不到根据参数配置决定是否走内部逻辑,通过内部逻辑查询到结果后,根据配置确定是否缓存,默认缓存结果;结构如下,常用属性如下
cacheNames、value : 对应的是CacheManager中获取Cache的name