我们使用Spring缓存框架进行缓存,我们希望能够为缓存支持多个命名空间,例如“book”或“isbn”,缓存命名空间是可配置的,而不是在类中硬编码,喜欢,而不是
@Cacheable({ "book","isbn"})
public Book findBook(ISBN isbn) {...}
我们希望能够以某种方式从属性文件中注入缓存名称,以便可以动态设置缓存名称,如:
@Cacheable({ #cachename1, #cachename2})
public Book findBook(ISBN isbn) {...}
我在这里使用SpEL,但不知道这是否可行。
答案 0 :(得分:2)
Spring 4.1引入了CacheResolver
,并使用自定义的CacheResolver
来选择Cache
,然后可以是动态的。 spring 4.1 cache impovements
答案 1 :(得分:1)
关闭smartwjw的答案......
我希望通过Spring环境变量解决cacheNames,例如@Cacheable("${my.config.property.name}")
。我通过自定义CacheResolver
import java.util.Collection;
import java.util.stream.Collectors;
import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.CacheOperationInvocationContext;
import org.springframework.cache.interceptor.SimpleCacheResolver;
import org.springframework.core.env.PropertyResolver;
public class PropertyResolvingCacheResolver
extends SimpleCacheResolver {
private final PropertyResolver propertyResolver;
protected PropertyResolvingCacheResolver(CacheManager cacheManager, PropertyResolver propertyResolver) {
super(cacheManager);
this.propertyResolver = propertyResolver;
}
@Override
protected Collection<String> getCacheNames(CacheOperationInvocationContext<?> context) {
Collection<String> unresolvedCacheNames = super.getCacheNames(context);
return unresolvedCacheNames.stream()
.map(unresolvedCacheName -> propertyResolver.resolveRequiredPlaceholders(unresolvedCacheName)).collect(Collectors.toList());
}
}
当然,您必须将其配置为CacheResolver
以与@Configuration
扩展org.springframework.cache.annotation.CachingConfigurerSupport
一起使用。
@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {
public static final String PROPERTY_RESOLVING_CACHE_RESOLVER_BEAN_NAME = "propertyResolvingCacheResolver";
@Autowired
private CacheManager cacheManager;
@Autowired
private Environment springEnv;
@Bean(PROPERTY_RESOLVING_CACHE_RESOLVER_BEAN_NAME)
@Override
public CacheResolver cacheResolver() {
return new PropertyResolvingCacheResolver(cacheManager, springEnv);
}
}
答案 2 :(得分:0)
@Cacheable注释的缓存名称(value
)属性不支持动态(SpEL或其他)表达式。您必须实现自己的org.springframework.cache.annotation.SpringCacheAnnotationParser
版本并将其注入框架。
答案 3 :(得分:0)
您也可以直接使用缓存,使所有内容更加可预测
EhCacheCacheManager cacheManager = (EhCacheCacheManager) CDBBeanFactory.instance().getBean("cacheManager");
CacheManager manager cacheManager.getCacheManager();
manager.getCache("cacheBin").get("key");
manager.getCache("cacheBin").put(new Element(key, obj));
等..