T. Jung
T. Jung

Reputation: 3657

How to cache mutiple lists using Spring SimpleCacheManager?

I'm writing a bookshop and i want to cache a List<Ebook> of ebooks and a list of normal books List<Book> so i don't have to call my database every time the page refreshes.

Right now i'm using the SimpleCacheManager and i define two differnt caches:

<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
    <property name="caches">
        <set>
            <bean
                class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
                p:name="bookList" />
            <bean
                class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
                p:name="ebookList" />
        </set>
    </property>
</bean>

If the showBookList(...) or showEbookList(...) is called the first time the List<...> is cached by a Service and if the page is reloaded the books/ebooks are loaded from the cache. If i add or delete an e-/book the service updates the cache. Is this the right way to do this or is there an easier way? I'm asking this because of this quote:

While in most cases, one cache is enough, the Spring framework also supports multiple caches to be passed as parameters.

So asked myself if my code is well written or just much too complicated. I'm using Spring 4.3.2 with Websphere Portal 8.5.5 and i'm building a JSR286 Portlet.

Upvotes: 1

Views: 517

Answers (1)

Taylor
Taylor

Reputation: 4087

A cache, at least in this context, can be thought of as a map. If you have two caches, you have two maps.

With spring caching, the default key generation is based on the method name and parameters, and will cache the return value. So each method is already going to end up in a distinct set of entries.

There are pros and cons to separate caches. Lookups can speed up because the set of keys to search is smaller, but this is usually trivial since hashmaps are pretty bloody fast these days, so you'd need a pretty huge map to benefit. The downside is the memory overhead and complexity of more caches to manage.

If your app is simple/small/not enterprise, I'd lean towards a single cache for simplicity's sake until/unless this shows problems.

Upvotes: 1

Related Questions