Monday, 21 September 2015

Implementing Spring caching in project @ Service Layer

Implementing Spring caching in project

STEP-1
Enabling Spring caching annotation:-

Define spring cache manager and enable the cache annotation in meta-configuration file

<cache:annotation-driven cache-manager="cacheManager" proxy-target-class="false"/>


STEP-2
Defining Spring cache manager..

<!-- generic cache manager -->
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
           <set>
  <bean class="org.springframework.cache.concurrent.
ConcurrentMapCacheFactoryBean" p:name="spring-mvcCache"/>
           </set>
</property>

</bean>

Note : Cache name is spring-mvcCache


STEP-3
Applying annotation on service layer...................

    @Cacheable(value="quote", key="#quoteNumber")
     public Quote getQuote(String quoteNumber) {
           Quote retrievedQuote = new Quote(quoteNumber);
           try {
            retrievedQuote = quoteRetrieveSAO.retrieve(quoteNumber);
          } catch (RetrieveException e) {
    log.fatal("Failed to retrieve quote from cache for quote number:" + quoteNumber, e);
           }
           return retrievedQuote;
     }

     @CachePut(value="quote", key="#quoteNumber")
     public Quote updateQuote(String quoteNumber, Quote quote) {
           return quote;
     }

     @Cacheable(value="quoteErrors", key="#quoteNumber")
     public List<CollectionSetError> getQuoteErrors(String quoteNumber) {
           return new ArrayList<CollectionSetError>();
     }


     @Override
     @CacheEvict(value="spring-mvcCache",allEntries=true)
     public void deleteAlbum(int albumId) {
           String sql = "delete from albums WHERE albumid = " + albumId + " ";
           getJdbcTemplate().update(sql);
     }






No comments:

Post a Comment