Spring Boot Tutorial

Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)

Prerequisite (Spring Core Concepts)

Spring Boot Core

Spring Boot with REST API

Spring Boot with Database and Data JPA

Spring Boot with Kafka

Spring Boot with AOP

Spring Boot - EhCaching

EhCache is a widely used Java-based cache solution that can be integrated into a Spring Boot application to improve performance by reducing unnecessary database reads or expensive computations. When you use EhCache with Spring Boot, the caching abstraction provided by Spring makes it easy to add caching capabilities to your application without being tightly coupled to a specific caching provider.

Here's a brief guide to integrating EhCache with a Spring Boot application:

  • Maven Dependencies: Add the necessary dependencies in your pom.xml:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>
  • Configuration: Create an ehcache.xml configuration file in the src/main/resources directory. This is where you define your cache configurations.
<ehcache>
    <diskStore path="java.io.tmpdir"/>

    <cache name="myCache"
           maxEntriesLocalHeap="1000"
           maxEntriesLocalDisk="1000"
           eternal="false"
           diskSpoolBufferSizeMB="20"
           timeToLiveSeconds="120"
           memoryStoreEvictionPolicy="LRU"
           transactionalMode="off">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>

This configuration defines a cache named myCache with various settings.

  • Spring Boot Configuration:

Enable caching in your Spring Boot application using the @EnableCaching annotation:

@SpringBootApplication
@EnableCaching
public class MySpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApplication.class, args);
    }
}

Also, configure the cache manager in a configuration class:

@Configuration
public class CacheConfig {
    @Bean
    public CacheManager cacheManager() {
        return new EhCacheCacheManager(ehCacheCacheManager().getObject());
    }

    @Bean
    public EhCacheManagerFactoryBean ehCacheCacheManager() {
        EhCacheManagerFactoryBean factoryBean = new EhCacheManagerFactoryBean();
        factoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
        factoryBean.setShared(true);
        return factoryBean;
    }
}
  • Usage:

You can use caching in your service or repository layers using annotations like @Cacheable, @CachePut, and @CacheEvict:

@Service
public class MyService {

    @Cacheable(value = "myCache", key = "#id")
    public MyObject findById(Long id) {
        // Some expensive computation or database call
    }

    @CacheEvict(value = "myCache", key = "#id")
    public void deleteById(Long id) {
        // Delete logic
    }
}

The @Cacheable annotation ensures that method results are stored in the cache, and future calls with the same arguments will retrieve the cached value instead of executing the method body. The @CacheEvict annotation ensures that an entry is removed from the cache.

  • Testing & Monitoring:

You can monitor the cache hit and miss ratio, the number of elements in the cache, and other metrics using JMX and integrating with monitoring tools like Micrometer and Prometheus.

In summary, integrating EhCache with a Spring Boot application is a straightforward process, providing an effective way to improve the performance of your applications by caching frequently accessed data or expensive computations.

  1. Configuring EhCache in Spring Boot:

    • Add EhCache dependencies to your pom.xml or build.gradle.
    • Configure ehcache.xml or use programmatic configuration.

    Example (pom.xml):

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>
    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache</artifactId>
    </dependency>
    
  2. Integration of EhCache with Spring Boot:

    • Spring Boot automatically configures EhCache based on dependencies.
    • Ensure @EnableCaching is present in your configuration.

    Example (Application class):

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cache.annotation.EnableCaching;
    
    @SpringBootApplication
    @EnableCaching
    public class MySpringBootApplication {
        public static void main(String[] args) {
            SpringApplication.run(MySpringBootApplication.class, args);
        }
    }
    
  3. Using EhCache for caching in Spring Boot applications:

    • Annotate methods with @Cacheable, @CachePut, or @CacheEvict.
    • Specify the cache name in annotations.

    Example (@Cacheable):

    import org.springframework.cache.annotation.Cacheable;
    
    public class MyService {
        @Cacheable("myCache")
        public String getCachedData(String key) {
            // Business logic to retrieve data
        }
    }
    
  4. Caching strategies and eviction policies with EhCache in Spring Boot:

    • Configure caching strategies and eviction policies in ehcache.xml.
    • Options include LRU, LFU, and time-based eviction.

    Example (ehcache.xml):

    <ehcache>
        <cache name="myCache" maxEntriesLocalHeap="100" eternal="false"
               timeToLiveSeconds="300" timeToIdleSeconds="120" />
    </ehcache>
    
  5. Customizing EhCache configuration in Spring Boot:

    • Customize EhCache configuration programmatically.
    • Extend CachingConfigurerSupport and override methods.

    Example (Custom Config):

    import org.springframework.cache.annotation.EnableCaching;
    import org.springframework.cache.annotation.CachingConfigurerSupport;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @EnableCaching
    public class CacheConfig extends CachingConfigurerSupport {
        // Custom configuration here
    }
    
  6. EhCache annotations and caching in Spring Boot:

    • Use @Cacheable, @CachePut, and @CacheEvict annotations.
    • Specify the cache name and key.

    Example (@CachePut):

    import org.springframework.cache.annotation.CachePut;
    
    public class MyService {
        @CachePut("myCache")
        public String updateCachedData(String key, String newData) {
            // Business logic to update and return data
        }
    }
    
  7. Monitoring and managing EhCache in Spring Boot:

    • EhCache provides monitoring tools.
    • Tools like JMX can be used for management.

    Example (JMX Configuration in ehcache.xml):

    <ehcache>
        <cacheManagerPeerProviderFactory
            class="net.sf.ehcache.management.ManagedPeerProviderFactory"
            properties="peerDiscovery=automatic, multicastGroupAddress=230.0.0.1, multicastGroupPort=4446"/>
    </ehcache>
    
  8. EhCache vs other caching providers in Spring Boot:

    • EhCache is one of several caching providers supported by Spring Boot.
    • Consider other options like Caffeine, Guava, or Redis based on requirements.

    Example (Using Caffeine):

    <dependency>
        <groupId>com.github.ben-manes.caffeine</groupId>
        <artifactId>caffeine</artifactId>
    </dependency>