-
Notifications
You must be signed in to change notification settings - Fork 39
在 crane4j 中,具体每个缓存对应一个缓存对象 Cache,数据源容器通过持有缓存对象获得缓存读写能力,所有的 Cache 都会被一个全局的缓存管理器 CacheManager 管理。
在 crane4j 中,缓存的数据以单个缓存对象 Cache 为单位进行管理,每个 Cache 都在 CacheManger 中对应一个唯一的 namespace,通过 namespace 即可从 CacheManager 中获得对应的缓存。
默认提供了缓存管理器的实现 SimpleCacheManager 和缓存对象的实现 ConcurrentMapCache ,在 Spring 环境中,会默认注册一个 SimpleCacheManager。若有必要,用户可以实现 CacheManager 接口并替换默认的缓存管理器,从而实现诸如 Redis 缓存(后期可能会提供默认实现),或者其他本地缓存。
容器缓存基于缓存容器包装类 CacheableContainer 实现,可以将任何容器包装为支持按 key 缓存的容器:
// 创建一个原始容器
Container<String> original = LambdaContainer.forLambda("original", keys -> {
Map<String, Object> map = new HashMap<>();
keys.forEach(key -> map.put(key, new Object()));
return map;
});
// 创建一个缓存对象
Cache<String> cache = new ConcurrentMapCache<>(new ConcurrentHashMap<>(2));
// 基于原始容器与缓存对象,构建带有缓存功能的容器
CacheableContainer<String> container = new CacheableContainer<>(container, cache);在 Spring 环境中,一般不需要手动创建缓存容器,可以基于配置直接将已有的容器升级为缓存容器。
缓存容器的创建需要基于已有容器。在 Spring 环境中,可以通过三种方式将容器配置为缓存容器:
手动替换
Crane4jApplicationContext context = StringUtils.getBean(Crane4jApplicationContext.class);
context.getRegisteredContainers().computeIfPresent("key", (key, container) -> {
// 创建一个缓存对象
Cache<String> cache = new ConcurrentMapCache<>(new ConcurrentHashMap<>(2));
// 基于原始容器与缓存对象,构建带有缓存功能的容器
return new CacheableContainer<>(container, cache);
})添加注解
仅针对通过 @ContainerMethod 声明的方法容器,可以在方法上添加 @ContainerCache 注解:
@ContainerCache // 声明该方法容器为可缓存容器
@ContainerMethod(resultType = Foo.class)
public List<Foo> oneToManyMethod(List<String> args) {
return args.stream().map(key -> new Foo(key, key)).collect(Collectors.toList());
}方法容器创建的过程中,将会根据 @ContainerCache 指定的 cacheName 从 Spring 上下文中的 CacheManager 获得对应的缓存。
配置文件
针对已经注册的容器,也可以通过配置文件声明:
crane4j:
cache-containers:
cache-name: container-namespace比如上述配置文件,将 container-namespace 对应的容器声明为了缓存容器,使用的缓存对应的名称为 cache-name。