Thursday, 12 November 2015

Spring Caching with ConcurrentMapCacheFactoryBean (Server side caching)

Step-1

create one xml file

spring-cache.xml

<!-- 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>

Step-2
Enabling Spring Cache Annotation and associating with spring cache manager 
@Cachable , @CacheEvict,@CachePut

@Cachable - 3 attributes
@CacheEvict - 5 attributes
@CachePut - 3 attributes


      <!-- 
      This for enabling Spring Cache annotation 
      -->
     <cache:annotation-driven cache-manager="cacheManager" proxy-target-class="false"/>


        CacheEvict Example

@Override
@CacheEvict(value="spring-mvcCache",key="#albumId",beforeInvocation=false)
public void deleteImage(int imageId) {
String sql = "delete from images WHERE imageId = " + imageId + " ";
getJdbcTemplate().update(sql);

}


        @CacheableExample
    
      @Cacheable(value="spring-mvcCache",key="#albumId")
@Override
public AlbumForm findCoverById(int albumId) {
String sql = "SELECT * FROM albums WHERE albumid = ?";
AlbumForm albumForm = (AlbumForm) getJdbcTemplate().queryForObject(sql,
new Object[] { albumId }, new AlbumRowMapper());
return albumForm;
}


   Annotation Description -Cacheable 

    /**
 * Annotation indicating that a method (or all the methods on a class) can be cached.
 *
 * <p>The method arguments and signature are used for computing the key while the
 * returned instance is used as the cache value.
 *
 * @author Costin Leau
 * @since 3.1
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Cacheable {
}


Annotation Description -CacheEvict 

/**
 * Annotation indicating that a method (or all methods on a class) trigger(s)
 * a cache invalidate operation.
 *
 * @author Costin Leau
 * @since 3.1
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented

public @interface CacheEvict {

}


Annotation Description -CachePut 

 /**
 * Annotation indicating that a method (or all methods on a class) trigger(s)
 * a {@link Cache#put(Object, Object)} operation. As opposed to {@link Cacheable} annotation,
 * this annotation does not cause the target method to be skipped - rather it
 * always causes the method to be invoked and its result to be placed into the cache.
 *
 * @author Costin Leau
 * @since 3.1
 */
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface CachePut {
}

1 comment: