Documente Academic
Documente Profesional
Documente Cultură
Created on: July 20, 2016 | Last updated on: September 30, 2017 websystiqueadmin
Like Page
Spring Cache Abstraction is a set of interfaces and annotations, used for applying Secure Spring REST API using
caching to Java methods. The idea is to cache the returned value of a method for OAuth2
a given input[method argument e.g.], and for any further request with same input,
return the result from cache without even executing the method, thus reducing the
websystique.com/spring/spring-4-cache-tutorial-with-ehcache/ 1/14
8/28/2019 Spring 4 Cache Tutorial with EhCache - WebSystique
Caching Providers/Implementations
Bangalore
WEBSITE DIRECTIONS
Caching Annotations
@Cacheable : triggers cache population
In this post, we will learn the basics of caching and commonly used annotations
including @EnableCaching , @Cacheable & @CacheEvict using EhCache
as caching provider.
websystique.com/spring/spring-4-cache-tutorial-with-ehcache/ 2/14
8/28/2019 Spring 4 Cache Tutorial with EhCache - WebSystique
Without Caching
In order to understand the need of caching and appreciate caching advantages,
lets first see an example where no caching is used.
package com.websystique.spring.model;
@Override
public String toString() {
return "Product [name=" + name + ", price=" + price + "]";
}
}
package com.websystique.spring.service;
import com.websystique.spring.model.Product;
package com.websystique.spring.service;
import org.springframework.stereotype.Service;
websystique.com/spring/spring-4-cache-tutorial-with-ehcache/ 3/14
8/28/2019 Spring 4 Cache Tutorial with EhCache - WebSystique
import com.websystique.spring.model.Product;
@Service("productService")
public class ProductServiceImpl implements ProductService{
@Override
public Product getByName(String name) {
slowLookupOperation();
return new Product(name,100);
}
package com.websystique.spring.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.AnnotationConfigAppl
import org.springframework.context.support.AbstractApplicationCont
import com.websystique.spring.service.ProductService;
If you run above example, following will be the output. Note that each lookup
takes 5 seconds, even if the product we are looking for is exactly same.
@Cacheable annotation indicates that the result of invoking a method (or all
methods in a class) can be cached. A cache itself can be imagined as a key-value
based Map. First time a method annotated with @Cacheable gets called, it gets
executed and it’s return value is stored in Cache using a key[method parameter
for instance, ]. Next time, if the method gets called using same key[same
parameter for instance], the result is returned directly from Cache, method
invocation does not take place.
By default it uses the method parameters [product name in this case] to compute
the key , but a SpEL expression can be provided via the key() attribute, or a
custom KeyGenerator implementation can replace the default one. Check out the
Official reference for details of all possible attributes.
package com.websystique.spring.service;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.websystique.spring.model.Product;
@Service("productService")
public class ProductServiceImpl implements ProductService{
@Override
@Cacheable("products")
public Product getByName(String name) {
slowLookupOperation();
return new Product(name,100);
}
websystique.com/spring/spring-4-cache-tutorial-with-ehcache/ 5/14
8/28/2019 Spring 4 Cache Tutorial with EhCache - WebSystique
package com.websystique.spring.configuration;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
@EnableCaching
@Configuration
@ComponentScan(basePackages = "com.websystique.spring")
public class AppConfig {
/*
//Suitable for basic use cases, no persistence capabilities or
@Bean
public CacheManager cacheManager() {
// configure and return an implementation of Spring's
SimpleCacheManager cacheManager = new SimpleCacheManag
cacheManager.setCaches(Arrays.asList(new ConcurrentMap
return cacheManager;
}
*/
@Bean
public EhCacheManagerFactoryBean ehCacheCacheManager() {
EhCacheManagerFactoryBean factory = new EhCacheManagerFact
factory.setConfigLocation(new ClassPathResource("ehcache.x
websystique.com/spring/spring-4-cache-tutorial-with-ehcache/ 6/14
8/28/2019 Spring 4 Cache Tutorial with EhCache - WebSystique
factory.setShared(true);
return factory;
}
org.springframework.cache.Cache &
org.springframework.cache.CacheManager are the main abstractions
provided by Spring. Please do note that these are the abstraction providing the
caching logic, but does not provide the actual storage to store the cache data.
Fortunately, there are few implementations of that abstraction available out of the
box: JDK java.util.concurrent.ConcurrentMap based caches, EhCache, Gemfire
cache, Caffeine, Guava caches and JSR-107 compliant caches.
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.2.2.21</version>
</dependency>
<cache name="products"
maxEntriesLocalHeap="100"
maxEntriesLocalDisk="1000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LFU"
transactionalMode="off">
<persistence strategy="localTempSwap" />
</cache>
</ehcache>
Here we are setting up a cache with name ‘products’. Maximum 100 products will
be kept in in-memory [on-heap] store, while maximum 1000 products will be
maintained in the DiskStore, on the path specified ‘java.io.tmpdir’ which refers to
websystique.com/spring/spring-4-cache-tutorial-with-ehcache/ 7/14
8/28/2019 Spring 4 Cache Tutorial with EhCache - WebSystique
default temp file path. A product will be expired if it is idle for more than 5 minutes
and lives for more than 10 minutes. A detailed description of individual properties
can be found at Ehcache Official Reference.
package com.websystique.spring.configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.AnnotationConfigAppl
import org.springframework.context.support.AbstractApplicationCont
import com.websystique.spring.service.ProductService;
((AbstractApplicationContext) context).close();
}
}
The output speaks for itself. For the 1st request, method was executed, while for
2nd, 3rd, we got them from cache. Then we fired a remove-all-products-from-
cache. 5th line shows that method was re-executed and took 5 seconds, while
6th,7th were again from cache.
In the next post, we will develop an interesting use case involving @CahcePut
along with other goodies we have seen here.Stay tune.
pom.xml
websystique.com/spring/spring-4-cache-tutorial-with-ehcache/ 8/14
8/28/2019 Spring 4 Cache Tutorial with EhCache - WebSystique
<groupId>com.websystique.spring</groupId>
<artifactId>Spring4CachingExample</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>Spring4CachingExample</name>
<properties>
<springframework.version>4.3.0.RELEASE</springframework.ve
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- EHCache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.2.2.21</version>
</dependency>
<!-- SLF4J/Logback -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Project Structure
websystique.com/spring/spring-4-cache-tutorial-with-ehcache/ 9/14
8/28/2019 Spring 4 Cache Tutorial with EhCache - WebSystique
That’s it. Next post discusses all Spring Cache annotations in detail with help of
examples.
Download Now!
References
websystiqueadmin
If you like tutorials on this site, why not take a step further and
connect me on Facebook , Google Plus & Twitter as well? I would
love to hear your thoughts on these articles, it will help improve
further our learning process.
Related Posts:
websystique.com/spring/spring-4-cache-tutorial-with-ehcache/ 10/14
8/28/2019 Spring 4 Cache Tutorial with EhCache - WebSystique
spring. permalink.
websystique.com/spring/spring-4-cache-tutorial-with-ehcache/ 11/14
8/28/2019 Spring 4 Cache Tutorial with EhCache - WebSystique
Sponsored Links
4 Comments websystique
1 Login
LOG IN WITH
OR SIGN UP WITH DISQUS ?
Name
After updating the selected entity, it seems the ehcache is not updating
the cache value. It's still showing the same data before updating. Even
refreshing many times. Hoping to find for solution for this, thanks
websystique! Big fan of this tutorial page.
△ ▽ • Reply • Share ›
websystique.com/spring/spring-4-cache-tutorial-with-ehcache/ 13/14
8/28/2019 Spring 4 Cache Tutorial with EhCache - WebSystique
websystique.com/spring/spring-4-cache-tutorial-with-ehcache/ 14/14