paramupk
paramupk

Reputation: 626

Spring Caching and hard coded cache name

I am using spring caching in my project using annotations. Based on profile I am using Elasticache and SimpleCacheManager. The annotations used are

//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(){
    ......
    }
}

I am forced to hard code cache name "MyCache" everywhere which I dont like. Is there a way to make this configurable. Somehow coming from a property file??

Upvotes: 3

Views: 1702

Answers (1)

Stephane Nicoll
Stephane Nicoll

Reputation: 33091

You have several options.

First of all, it is Java so you can create a constant somewhere and refer to it. Then those places allow for SpEL so you can write ${myCache} and have a myCache property in the environment that has the value of your cache.

Finally, rather than specifying the cache names in code (be it using SpEL or not) you can implement CacheResolver and decide which cache to use programmatically. It's more work and probably overkill if you don't need to change the cache to use according to some business logic.

Part of the smell it annoys you is that you are maybe using the same cache for too many things. That key attribute in your last example looks mental to me: if you need to add the name of the class and the method to the key, it tells me you're trying to put way too many things in the same cache. You shouldn't design your cache like that: do not forget it is just a shortcut so that you don't have to do this manually. If you want to query the cache for a value, are you seriously going to use the name of the class and the method to compute the key?

Upvotes: 1

Related Questions