8

我们使用 Spring 缓存框架进行缓存,我们希望能够支持多个缓存命名空间,例如“book”或“isbn”,缓存命名空间是可配置的,而不是在类中硬编码,例如,具有

@Cacheable({ "book","isbn"})
public Book findBook(ISBN isbn) {...}

我们希望能够以某种方式从属性文件中注入缓存名称,以便可以动态设置缓存名称,例如:

@Cacheable({ #cachename1, #cachename2})
public Book findBook(ISBN isbn) {...}

我在这里使用SpEL,但不知道这是否可行。

4

4 回答 4

8

离开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());
    }
}

然后当然您必须将其配置为 THECacheResolver才能与@Configurationthat extends一起使用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);
    }
}
于 2017-08-17T17:50:50.647 回答
3

Spring 4.1 引入了CacheResolver,并且使用你自定义CacheResolver的选择Cache然后可以是动态的。spring 4.1 缓存改进

于 2016-01-21T10:09:49.777 回答
0

value不,@ Cacheable 注释的缓存名称 ( ) 属性不支持动态(SpEL 或其他)表达式。您必须实现自己的版本org.springframework.cache.annotation.SpringCacheAnnotationParser并将其注入框架。

于 2012-11-02T08:03:06.770 回答
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));

ETC ..

于 2015-05-15T13:33:05.583 回答