Spring Caching和硬编码缓存名称

时间:2016-10-07 00:12:19

标签: annotations spring-cloud spring-cache

我在使用注释的项目中使用spring缓存。基于配置文件我使用Elasticache和SimpleCacheManager。使用的注释是

//For the initial configuration settings in some class when profile is cloud.
@EnableElastiCache({@CacheClusterConfig(name = "MyCache", expiration = 86400)}) 

// For the initial configuration settings in some class when profile is non-cloud. 
SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
        simpleCacheManager.setCaches(newArrayList(new ConcurrentMapCache("MyCache")));



@CacheConfig(cacheNames = {"MyCache"})
public class CachingRequiredClass{
........
    @Cacheable
    public String blablaMethod(String id){
    .....
    }
}

public class SomeOtherClass{
    ......
    @Caching(evict={
        @CacheEvict(value="MyCache", key="T(com.myclass).myMethod()+':blablaMethod()'"),
        @CacheEvict(value="MyCache", key="T(com.myclass).myMethod()+':blablaMethod()+':blablabla2Method()'")
    })
    public void logout(){
    ......
    }
}

我被迫硬编码缓存名称“MyCache”到处都是我不喜欢的。有没有办法使这个可配置。不知何故来自属性文件??

1 个答案:

答案 0 :(得分:1)

您有几种选择。

首先,它是Java,所以你可以在某处创建一个常量并引用它。然后这些地方允许SpEL,因此您可以在具有缓存值的环境中编写${myCache}并拥有myCache属性。

最后,不是在代码中指定缓存名称(无论是否使用SpEL),您可以实现CacheResolver并决定以编程方式使用哪个缓存。如果您不需要根据某些业务逻辑更改要使用的缓存,那么它的工作量可能会有所超出。

它让你烦恼的部分气味是你可能使用相同的缓存来处理太多事情。你上一个例子中的key属性看起来很精神:如果你需要将类的名称和方法添加到密钥中,它会告诉我你试图把太多的东西放在相同的缓存。您不应该像这样设计缓存:不要忘记它只是一个快捷方式,因此您不必手动执行此操作。如果要查询缓存中的值,是否真的要使用类的名称和方法来计算密钥?