DEV Community

Cover image for How to Configure Spring Boot with Memcached
Nikhil Soman Sahu
Nikhil Soman Sahu

Posted on

How to Configure Spring Boot with Memcached

Introduction:

Caching is a fundamental performance optimization technique for read-heavy database applications. With the release of Spring 3.1, developers gained access to the Cache Abstraction feature, which provides an easy, transparent, and decoupled way to implement caching solutions. Memcached is a popular distributed caching system widely used across applications. In this blog post, we'll focus on how to integrate Memcached with Spring-enabled applications using the Simple Spring Memcache (SSM) library, as Spring directly supports only Ehcache and ConcurrentHashMap.

Image description

Getting Started:

  1. Dependencies: Add the following dependencies to your project's POM file:
<dependency>
    <groupId>com.google.code.simple-spring-memcached</groupId>
    <artifactId>spring-cache</artifactId>
    <version>3.1.0</version>
</dependency>

<dependency>
    <groupId>com.google.code.simple-spring-memcached</groupId>
    <artifactId>xmemcached-provider</artifactId>
    <version>3.1.0</version>
</dependency>
Enter fullscreen mode Exit fullscreen mode
  1. Enable Caching: To enable caching in your Spring application, add the following line to your Spring context XML:
<cache:annotation-driven/>
Enter fullscreen mode Exit fullscreen mode
  1. Configure Spring for Memcached Caching: Add the following configuration to your application context XML:
<bean name="cacheManager" class="com.google.code.ssm.spring.SSMCacheManager">
    <property name="caches">
        <set>
            <bean class="com.google.code.ssm.spring.SSMCache">
                <constructor-arg name="cache" index="0" ref="defaultCache"/>
                <constructor-arg name="expiration" index="1" value="300"/>
                <constructor-arg name="allowClear" index="2" value="false"/>
            </bean>
        </set>
    </property>
</bean>

<bean name="defaultCache" class="com.google.code.ssm.CacheFactory">
    <property name="cacheName" value="defaultCache"/>
    <property name="cacheClientFactory">
        <bean name="cacheClientFactory" class="com.google.code.ssm.providers.xmemcached.MemcacheClientFactoryImpl"/>
    </property>
    <property name="addressProvider">
        <bean class="com.google.code.ssm.config.DefaultAddressProvider">
            <property name="address" value="127.0.0.1:11211"/>
        </bean>
    </property>
    <property name="configuration">
        <bean class="com.google.code.ssm.providers.CacheConfiguration">
            <property name="consistentHashing" value="true"/>
        </bean>
    </property>
</bean>
Enter fullscreen mode Exit fullscreen mode

This configuration sets up the SSMCacheManager and SSMCache beans, which are responsible for managing the underlying cache and interacting with Memcached.

  1. Annotation-Driven Caching: Spring provides the following annotations for cache management:
  • @Cacheable: Marks a method whose results should be cached. If the method is called and the result is already in the cache, the cached value is returned. Otherwise, the method is executed, and the result is cached.
  • @CachePut: Methods marked with this annotation are always executed, and their results are pushed to the cache.
  • @CacheEvict: This annotation triggers the eviction of objects from the cache, typically used when the result object is updated, and the old object needs to be purged from the cache.
  • @Caching: Used when multiple annotations of the same type need to be placed on a method.

Here are some examples of using these annotations:

@Cacheable Demo:

@Cacheable(value = "defaultCache", key = "new Integer(#book_id).toString().concat('.BookVO')")
public BookVO get(int book_id) throws Exception {
    // Code to retrieve BookVO from the database
}
Enter fullscreen mode Exit fullscreen mode

In this example, the get method is marked with @Cacheable, and the result BookVO object will be cached using a key based on the book_id parameter.

@CachePut Demo:

@CachePut(value = "defaultCache", key = "new Integer(#bookVO.book_id).toString().concat('.BookVO')")
public BookVO create(BookVO bookVO) throws Exception {
    // Code to insert the BookVO into the database
    return bookVO;
}
Enter fullscreen mode Exit fullscreen mode

The create method is marked with @CachePut, which means that after inserting the BookVO into the database, the result will be cached using a key based on the book_id property.

@CacheEvict Demo:

@CacheEvict(value = "defaultCache", key = "new Integer(#bookVO.book_id).toString().concat('.BookVO')")
public BookVO update(BookVO bookVO) throws Exception {
    // Code to update the BookVO in the database
    return bookVO;
}
Enter fullscreen mode Exit fullscreen mode

In this example, the update method is marked with @CacheEvict, which will evict the cached BookVO object from the cache, using a key based on the book_id property. This ensures that the next time the get method is called for the updated BookVO, it will fetch the latest data from the database.

Conclusion:

By integrating Memcached with Spring using the Simple Spring Memcache library, you can easily leverage the power of distributed caching in your Spring-enabled applications. The Cache Abstraction feature and annotations like @Cacheable, @CachePut, and @CacheEvict provide a convenient way to manage caching logic, improving application performance and reducing database load.

Resources

[Resource 1 ](https://code.google.com/p/simple-spring-memcached/)
[Resource 2](http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/cache.html)
[Resource 3](http://static.springsource.org/spring/docs/3.1.0.M1/javadoc-api/index.html?org/springframework/cache/CacheManager.html)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)