extract spring-caching module

This commit is contained in:
Denis 2019-08-31 15:51:56 +02:00
parent 9fd2fb32ca
commit e848a0ffcf
25 changed files with 338 additions and 299 deletions

View File

@ -17,15 +17,12 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Running Setup Data on Startup in Spring](http://www.baeldung.com/running-setup-logic-on-startup-in-spring) - [Running Setup Data on Startup in Spring](http://www.baeldung.com/running-setup-logic-on-startup-in-spring)
- [Quick Guide to Spring Controllers](http://www.baeldung.com/spring-controllers) - [Quick Guide to Spring Controllers](http://www.baeldung.com/spring-controllers)
- [Quick Guide to Spring Bean Scopes](http://www.baeldung.com/spring-bean-scopes) - [Quick Guide to Spring Bean Scopes](http://www.baeldung.com/spring-bean-scopes)
- [Introduction To Ehcache](http://www.baeldung.com/ehcache)
- [Custom Scope in Spring](http://www.baeldung.com/spring-custom-scope) - [Custom Scope in Spring](http://www.baeldung.com/spring-custom-scope)
- [A CLI with Spring Shell](http://www.baeldung.com/spring-shell-cli) - [A CLI with Spring Shell](http://www.baeldung.com/spring-shell-cli)
- [JasperReports with Spring](http://www.baeldung.com/spring-jasper) - [JasperReports with Spring](http://www.baeldung.com/spring-jasper)
- [Model, ModelMap, and ModelView in Spring MVC](http://www.baeldung.com/spring-mvc-model-model-map-model-view) - [Model, ModelMap, and ModelView in Spring MVC](http://www.baeldung.com/spring-mvc-model-model-map-model-view)
- [A Guide To Caching in Spring](http://www.baeldung.com/spring-cache-tutorial)
- [@Order in Spring](http://www.baeldung.com/spring-order) - [@Order in Spring](http://www.baeldung.com/spring-order)
- [Spring Web Contexts](http://www.baeldung.com/spring-web-contexts) - [Spring Web Contexts](http://www.baeldung.com/spring-web-contexts)
- [Spring Cache Creating a Custom KeyGenerator](http://www.baeldung.com/spring-cache-custom-keygenerator)
- [Spring @Primary Annotation](http://www.baeldung.com/spring-primary) - [Spring @Primary Annotation](http://www.baeldung.com/spring-primary)
- [Spring Events](https://www.baeldung.com/spring-events) - [Spring Events](https://www.baeldung.com/spring-events)
- [Spring Null-Safety Annotations](https://www.baeldung.com/spring-null-safety-annotations) - [Spring Null-Safety Annotations](https://www.baeldung.com/spring-null-safety-annotations)

View File

@ -147,10 +147,6 @@
<version>${easymock.version}</version> <version>${easymock.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.apache.logging.log4j</groupId> <groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId> <artifactId>log4j-api</artifactId>
@ -243,7 +239,6 @@
<!-- util --> <!-- util -->
<guava.version>25.1-jre</guava.version> <guava.version>25.1-jre</guava.version>
<ehcache.version>3.5.2</ehcache.version>
<easymock.version>3.6</easymock.version> <easymock.version>3.6</easymock.version>
<assertj.version>3.6.1</assertj.version> <assertj.version>3.6.1</assertj.version>
<jasperreports.version>6.6.0</jasperreports.version> <jasperreports.version>6.6.0</jasperreports.version>

View File

@ -1,4 +1,4 @@
package org.baeldung.model; package org.baeldung.caching.model;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;

View File

@ -1,6 +1,6 @@
package org.baeldung.repository; package org.baeldung.repository;
import org.baeldung.model.User; import org.baeldung.caching.model.User;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;

View File

@ -1,7 +1,7 @@
package org.baeldung.repository; package org.baeldung.repository;
import org.baeldung.boot.config.H2JpaConfig; import org.baeldung.boot.config.H2JpaConfig;
import org.baeldung.model.User; import org.baeldung.caching.model.User;
import org.junit.After; import org.junit.After;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;

4
spring-caching/README.md Normal file
View File

@ -0,0 +1,4 @@
### Relevant articles:
- [Introduction To Ehcache](http://www.baeldung.com/ehcache)
- [A Guide To Caching in Spring](http://www.baeldung.com/spring-cache-tutorial)
- [Spring Cache Creating a Custom KeyGenerator](http://www.baeldung.com/spring-cache-custom-keygenerator)

43
spring-caching/pom.xml Normal file
View File

@ -0,0 +1,43 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-caching</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-caching</name>
<packaging>war</packaging>
<parent>
<artifactId>parent-boot-2</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<ehcache.version>3.5.2</ehcache.version>
</properties>
</project>

View File

@ -1,18 +1,18 @@
package org.baeldung.caching.eviction.controllers; package org.baeldung.caching.eviction.controllers;
import org.baeldung.caching.eviction.service.CachingService; import org.baeldung.caching.eviction.service.CachingService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
public class CachingController { public class CachingController {
@Autowired @Autowired
CachingService cachingService; CachingService cachingService;
@GetMapping("clearAllCaches") @GetMapping("clearAllCaches")
public void clearAllCaches() { public void clearAllCaches() {
cachingService.evictAllCaches(); cachingService.evictAllCaches();
} }
} }

View File

@ -1,53 +1,53 @@
package org.baeldung.caching.eviction.service; package org.baeldung.caching.eviction.service;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager; import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CacheEvict;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Component @Component
public class CachingService { public class CachingService {
@Autowired @Autowired
CacheManager cacheManager; CacheManager cacheManager;
public void putToCache(String cacheName, String key, String value) { public void putToCache(String cacheName, String key, String value) {
cacheManager.getCache(cacheName).put(key, value); cacheManager.getCache(cacheName).put(key, value);
} }
public String getFromCache(String cacheName, String key) { public String getFromCache(String cacheName, String key) {
String value = null; String value = null;
if (cacheManager.getCache(cacheName).get(key) != null) { if (cacheManager.getCache(cacheName).get(key) != null) {
value = cacheManager.getCache(cacheName).get(key).get().toString(); value = cacheManager.getCache(cacheName).get(key).get().toString();
} }
return value; return value;
} }
@CacheEvict(value = "first", key = "#cacheKey") @CacheEvict(value = "first", key = "#cacheKey")
public void evictSingleCacheValue(String cacheKey) { public void evictSingleCacheValue(String cacheKey) {
} }
@CacheEvict(value = "first", allEntries = true) @CacheEvict(value = "first", allEntries = true)
public void evictAllCacheValues() { public void evictAllCacheValues() {
} }
public void evictSingleCacheValue(String cacheName, String cacheKey) { public void evictSingleCacheValue(String cacheName, String cacheKey) {
cacheManager.getCache(cacheName).evict(cacheKey); cacheManager.getCache(cacheName).evict(cacheKey);
} }
public void evictAllCacheValues(String cacheName) { public void evictAllCacheValues(String cacheName) {
cacheManager.getCache(cacheName).clear(); cacheManager.getCache(cacheName).clear();
} }
public void evictAllCaches() { public void evictAllCaches() {
cacheManager.getCacheNames() cacheManager.getCacheNames()
.parallelStream() .parallelStream()
.forEach(cacheName -> cacheManager.getCache(cacheName).clear()); .forEach(cacheName -> cacheManager.getCache(cacheName).clear());
} }
@Scheduled(fixedRate = 6000) @Scheduled(fixedRate = 6000)
public void evictAllcachesAtIntervals() { public void evictAllcachesAtIntervals() {
evictAllCaches(); evictAllCaches();
} }
} }

View File

@ -1,6 +1,6 @@
package org.baeldung.caching.example; package org.baeldung.caching.example;
import org.baeldung.model.Book; import org.baeldung.caching.model.Book;
import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;

View File

@ -1,4 +1,4 @@
package org.baeldung.model; package org.baeldung.caching.model;
public class Book { public class Book {

View File

@ -1,79 +1,79 @@
package org.baeldung.caching.test; package org.baeldung.caching.test;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.baeldung.caching.eviction.service.CachingService; import org.baeldung.caching.eviction.service.CachingService;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache; import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager; import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean; import org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean;
import org.springframework.cache.support.SimpleCacheManager; import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration @ContextConfiguration
public class CacheEvictAnnotationIntegrationTest { public class CacheEvictAnnotationIntegrationTest {
@Configuration @Configuration
@EnableCaching @EnableCaching
static class ContextConfiguration { static class ContextConfiguration {
@Bean @Bean
public CachingService cachingService() { public CachingService cachingService() {
return new CachingService(); return new CachingService();
} }
@Bean @Bean
public CacheManager cacheManager(){ public CacheManager cacheManager(){
SimpleCacheManager cacheManager = new SimpleCacheManager(); SimpleCacheManager cacheManager = new SimpleCacheManager();
List<Cache> caches = new ArrayList<>(); List<Cache> caches = new ArrayList<>();
caches.add(cacheBean().getObject()); caches.add(cacheBean().getObject());
cacheManager.setCaches(caches ); cacheManager.setCaches(caches );
return cacheManager; return cacheManager;
} }
@Bean @Bean
public ConcurrentMapCacheFactoryBean cacheBean(){ public ConcurrentMapCacheFactoryBean cacheBean(){
ConcurrentMapCacheFactoryBean cacheFactoryBean = new ConcurrentMapCacheFactoryBean(); ConcurrentMapCacheFactoryBean cacheFactoryBean = new ConcurrentMapCacheFactoryBean();
cacheFactoryBean.setName("first"); cacheFactoryBean.setName("first");
return cacheFactoryBean; return cacheFactoryBean;
} }
} }
@Autowired @Autowired
CachingService cachingService; CachingService cachingService;
@Before @Before
public void before() { public void before() {
cachingService.putToCache("first", "key1", "Baeldung"); cachingService.putToCache("first", "key1", "Baeldung");
cachingService.putToCache("first", "key2", "Article"); cachingService.putToCache("first", "key2", "Article");
} }
@Test @Test
public void givenFirstCache_whenSingleCacheValueEvictRequested_thenEmptyCacheValue() { public void givenFirstCache_whenSingleCacheValueEvictRequested_thenEmptyCacheValue() {
cachingService.evictSingleCacheValue("key1"); cachingService.evictSingleCacheValue("key1");
String key1 = cachingService.getFromCache("first", "key1"); String key1 = cachingService.getFromCache("first", "key1");
assertThat(key1, is(nullValue())); assertThat(key1, is(nullValue()));
} }
@Test @Test
public void givenFirstCache_whenAllCacheValueEvictRequested_thenEmptyCache() { public void givenFirstCache_whenAllCacheValueEvictRequested_thenEmptyCache() {
cachingService.evictAllCacheValues(); cachingService.evictAllCacheValues();
String key1 = cachingService.getFromCache("first", "key1"); String key1 = cachingService.getFromCache("first", "key1");
String key2 = cachingService.getFromCache("first", "key2"); String key2 = cachingService.getFromCache("first", "key2");
assertThat(key1, is(nullValue())); assertThat(key1, is(nullValue()));
assertThat(key2, is(nullValue())); assertThat(key2, is(nullValue()));
} }
} }

View File

@ -1,96 +1,96 @@
package org.baeldung.caching.test; package org.baeldung.caching.test;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.baeldung.caching.eviction.service.CachingService; import org.baeldung.caching.eviction.service.CachingService;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache; import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager; import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean; import org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean;
import org.springframework.cache.support.SimpleCacheManager; import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration @ContextConfiguration
public class CacheManagerEvictIntegrationTest { public class CacheManagerEvictIntegrationTest {
@Configuration @Configuration
static class ContextConfiguration { static class ContextConfiguration {
@Bean @Bean
public CachingService cachingService() { public CachingService cachingService() {
return new CachingService(); return new CachingService();
} }
@Bean @Bean
public CacheManager cacheManager(){ public CacheManager cacheManager(){
SimpleCacheManager cacheManager = new SimpleCacheManager(); SimpleCacheManager cacheManager = new SimpleCacheManager();
List<Cache> caches = new ArrayList<>(); List<Cache> caches = new ArrayList<>();
caches.add(cacheBeanFirst().getObject()); caches.add(cacheBeanFirst().getObject());
caches.add(cacheBeanSecond().getObject()); caches.add(cacheBeanSecond().getObject());
cacheManager.setCaches(caches ); cacheManager.setCaches(caches );
return cacheManager; return cacheManager;
} }
@Bean @Bean
public ConcurrentMapCacheFactoryBean cacheBeanFirst(){ public ConcurrentMapCacheFactoryBean cacheBeanFirst(){
ConcurrentMapCacheFactoryBean cacheFactoryBean = new ConcurrentMapCacheFactoryBean(); ConcurrentMapCacheFactoryBean cacheFactoryBean = new ConcurrentMapCacheFactoryBean();
cacheFactoryBean.setName("first"); cacheFactoryBean.setName("first");
return cacheFactoryBean; return cacheFactoryBean;
} }
@Bean @Bean
public ConcurrentMapCacheFactoryBean cacheBeanSecond(){ public ConcurrentMapCacheFactoryBean cacheBeanSecond(){
ConcurrentMapCacheFactoryBean cacheFactoryBean = new ConcurrentMapCacheFactoryBean(); ConcurrentMapCacheFactoryBean cacheFactoryBean = new ConcurrentMapCacheFactoryBean();
cacheFactoryBean.setName("second"); cacheFactoryBean.setName("second");
return cacheFactoryBean; return cacheFactoryBean;
} }
} }
@Autowired @Autowired
CachingService cachingService; CachingService cachingService;
@Before @Before
public void before() { public void before() {
cachingService.putToCache("first", "key1", "Baeldung"); cachingService.putToCache("first", "key1", "Baeldung");
cachingService.putToCache("first", "key2", "Article"); cachingService.putToCache("first", "key2", "Article");
cachingService.putToCache("second", "key", "Article"); cachingService.putToCache("second", "key", "Article");
} }
@Test @Test
public void givenFirstCache_whenSingleCacheValueEvictRequested_thenEmptyCacheValue() { public void givenFirstCache_whenSingleCacheValueEvictRequested_thenEmptyCacheValue() {
cachingService.evictSingleCacheValue("first", "key1"); cachingService.evictSingleCacheValue("first", "key1");
String key1 = cachingService.getFromCache("first", "key1"); String key1 = cachingService.getFromCache("first", "key1");
assertThat(key1, is(nullValue())); assertThat(key1, is(nullValue()));
} }
@Test @Test
public void givenFirstCache_whenAllCacheValueEvictRequested_thenEmptyCache() { public void givenFirstCache_whenAllCacheValueEvictRequested_thenEmptyCache() {
cachingService.evictAllCacheValues("first"); cachingService.evictAllCacheValues("first");
String key1 = cachingService.getFromCache("first", "key1"); String key1 = cachingService.getFromCache("first", "key1");
String key2 = cachingService.getFromCache("first", "key2"); String key2 = cachingService.getFromCache("first", "key2");
assertThat(key1, is(nullValue())); assertThat(key1, is(nullValue()));
assertThat(key2, is(nullValue())); assertThat(key2, is(nullValue()));
} }
@Test @Test
public void givenAllCaches_whenAllCacheEvictRequested_thenEmptyAllCaches() { public void givenAllCaches_whenAllCacheEvictRequested_thenEmptyAllCaches() {
cachingService.evictAllCaches(); cachingService.evictAllCaches();
String key1 = cachingService.getFromCache("first", "key1"); String key1 = cachingService.getFromCache("first", "key1");
assertThat(key1, is(nullValue())); assertThat(key1, is(nullValue()));
String key = cachingService.getFromCache("second", "key"); String key = cachingService.getFromCache("second", "key");
assertThat(key, is(nullValue())); assertThat(key, is(nullValue()));
} }
} }

View File

@ -1,40 +1,40 @@
package org.baeldung.ehcache; package org.baeldung.ehcache;
import org.baeldung.ehcache.calculator.SquaredCalculator; import org.baeldung.ehcache.calculator.SquaredCalculator;
import org.baeldung.ehcache.config.CacheHelper; import org.baeldung.ehcache.config.CacheHelper;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
public class SquareCalculatorUnitTest { public class SquareCalculatorUnitTest {
private SquaredCalculator squaredCalculator = new SquaredCalculator(); private SquaredCalculator squaredCalculator = new SquaredCalculator();
private CacheHelper cacheHelper = new CacheHelper(); private CacheHelper cacheHelper = new CacheHelper();
@Before @Before
public void setup() { public void setup() {
squaredCalculator.setCache(cacheHelper); squaredCalculator.setCache(cacheHelper);
} }
@Test @Test
public void whenCalculatingSquareValueOnce_thenCacheDontHaveValues() { public void whenCalculatingSquareValueOnce_thenCacheDontHaveValues() {
for (int i = 10; i < 15; i++) { for (int i = 10; i < 15; i++) {
assertFalse(cacheHelper.getSquareNumberCache().containsKey(i)); assertFalse(cacheHelper.getSquareNumberCache().containsKey(i));
System.out.println("Square value of " + i + " is: " + squaredCalculator.getSquareValueOfNumber(i) + "\n"); System.out.println("Square value of " + i + " is: " + squaredCalculator.getSquareValueOfNumber(i) + "\n");
} }
} }
@Test @Test
public void whenCalculatingSquareValueAgain_thenCacheHasAllValues() { public void whenCalculatingSquareValueAgain_thenCacheHasAllValues() {
for (int i = 10; i < 15; i++) { for (int i = 10; i < 15; i++) {
assertFalse(cacheHelper.getSquareNumberCache().containsKey(i)); assertFalse(cacheHelper.getSquareNumberCache().containsKey(i));
System.out.println("Square value of " + i + " is: " + squaredCalculator.getSquareValueOfNumber(i) + "\n"); System.out.println("Square value of " + i + " is: " + squaredCalculator.getSquareValueOfNumber(i) + "\n");
} }
for (int i = 10; i < 15; i++) { for (int i = 10; i < 15; i++) {
assertTrue(cacheHelper.getSquareNumberCache().containsKey(i)); assertTrue(cacheHelper.getSquareNumberCache().containsKey(i));
System.out.println("Square value of " + i + " is: " + squaredCalculator.getSquareValueOfNumber(i) + "\n"); System.out.println("Square value of " + i + " is: " + squaredCalculator.getSquareValueOfNumber(i) + "\n");
} }
} }
} }