简体   繁体   中英

Spring Cache, how should I design the caches and keys?

I am new to Spring Cache and using Ehcache as Spring Cache implemention.
I want to know about the following patterns: which one is better and why?

Pattern 1: many different classes use the same cache, with different key prefix.

@Cacheable(cacheNames = "myCache", key = "'user:'+#id")
public User findOne(int id) {
    return...
}

@Cacheable(cacheNames = "myCache", key = "'post:'+#id")
public Post findOne(int id) {
    return...
}

Pattern 2: Every class has its own cache.

@Cacheable(cacheNames = "users", key = "#id")
public User findOne(int id) {
    return...
}
@Cacheable(cacheNames = "posts", key = "#id")
public Post findOne(int id) {
    return...
}

With Pattern 2, I have to configure many <cache/> in my ehcache.xml.
I don't know whether Cache is a heavyweight component or not?
Is creating many Caches harmful to performance?

The second solution looks more effective and traceable and not error prone.

In some databases generated ids for different tables may conflict . So, for the first solution, you may have problems if one of the posts has same id with one of the users. In this version you won't need workarounds as you do in the first solution.

Second, you may want to have different attributes for different type of objects. For instance; timeToLiveSeconds . User information may change more often than posts. (eg number of entries for user etc.)

Third, maxEntriesLocalHeap . Keeping most recent objects from different types in heap looks like a better option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM