JAVA-13870 Move spring-caching,spring-caching-2 to spring-boot-module… (#13457)
* JAVA-13870 Move spring-caching,spring-caching-2 to spring-boot-modules (conti-1) * JAVA-13870 Making spring boot as the parent for spring-caching and spring caching-2 --------- Co-authored-by: timis1 <noreplay@yahoo.com>
This commit is contained in:
8
spring-boot-modules/spring-caching/README.md
Normal file
8
spring-boot-modules/spring-caching/README.md
Normal file
@@ -0,0 +1,8 @@
|
||||
### 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)
|
||||
- [Cache Eviction in Spring Boot](https://www.baeldung.com/spring-boot-evict-cache)
|
||||
- [Using Multiple Cache Managers in Spring](https://www.baeldung.com/spring-multiple-cache-managers)
|
||||
- [Testing @Cacheable on Spring Data Repositories](https://www.baeldung.com/spring-data-testing-cacheable)
|
||||
- [Spring Boot Ehcache Example](https://www.baeldung.com/spring-boot-ehcache)
|
||||
83
spring-boot-modules/spring-caching/pom.xml
Normal file
83
spring-boot-modules/spring-caching/pom.xml
Normal file
@@ -0,0 +1,83 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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>
|
||||
<groupId>com.baeldung.spring-boot-modules</groupId>
|
||||
<artifactId>spring-boot-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-cache</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.cache</groupId>
|
||||
<artifactId>cache-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.ehcache</groupId>
|
||||
<artifactId>ehcache</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.ben-manes.caffeine</groupId>
|
||||
<artifactId>caffeine</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jdbc</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>1.18.12</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-jpa</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-commons</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<ehcache.version>3.5.2</ehcache.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.cachetest;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.cachetest.config;
|
||||
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@EnableCaching
|
||||
public class CacheConfig {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.cachetest.config;
|
||||
|
||||
import org.ehcache.event.CacheEvent;
|
||||
import org.ehcache.event.CacheEventListener;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class CacheEventLogger implements CacheEventListener<Object, Object> {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(CacheEventLogger.class);
|
||||
|
||||
@Override
|
||||
public void onEvent(CacheEvent<? extends Object, ? extends Object> cacheEvent) {
|
||||
log.info("Cache event {} for item with key {}. Old value = {}, New value = {}", cacheEvent.getType(), cacheEvent.getKey(), cacheEvent.getOldValue(), cacheEvent.getNewValue());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.cachetest.rest;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.cachetest.service.NumberService;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(path = "/number", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
|
||||
public class NumberController {
|
||||
|
||||
private final static Logger log = LoggerFactory.getLogger(NumberController.class);
|
||||
|
||||
@Autowired
|
||||
private NumberService numberService;
|
||||
|
||||
@GetMapping(path = "/square/{number}")
|
||||
public String getThing(@PathVariable Long number) {
|
||||
log.info("call numberService to square {}", number);
|
||||
return String.format("{\"square\": %s}", numberService.square(number));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.cachetest.service;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class NumberService {
|
||||
|
||||
private final static Logger log = LoggerFactory.getLogger(NumberService.class);
|
||||
|
||||
@Cacheable(value = "squareCache", key = "#number", condition = "#number>10")
|
||||
public BigDecimal square(Long number) {
|
||||
BigDecimal square = BigDecimal.valueOf(number)
|
||||
.multiply(BigDecimal.valueOf(number));
|
||||
log.info("square of {} is {}", number, square);
|
||||
return square;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.caching.boot;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
//import org.springframework.context.annotation.ComponentScan;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableCaching
|
||||
//to run any module like ehcache,caching or multiplecachemanager in local machine
|
||||
//add it's package for ComponentScan like below
|
||||
//@ComponentScan("com.baeldung.multiplecachemanager")
|
||||
public class CacheApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(CacheApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.caching.boot;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.autoconfigure.cache.CacheManagerCustomizer;
|
||||
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import static java.util.Arrays.asList;
|
||||
|
||||
@Component
|
||||
public class SimpleCacheCustomizer implements CacheManagerCustomizer<ConcurrentMapCacheManager> {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleCacheCustomizer.class);
|
||||
|
||||
static final String USERS_CACHE = "users";
|
||||
static final String TRANSACTIONS_CACHE = "transactions";
|
||||
|
||||
@Override
|
||||
public void customize(ConcurrentMapCacheManager cacheManager) {
|
||||
LOGGER.info("Customizing Cache Manager");
|
||||
cacheManager.setCacheNames(asList(USERS_CACHE, TRANSACTIONS_CACHE));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.caching.config;
|
||||
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.cache.concurrent.ConcurrentMapCache;
|
||||
import org.springframework.cache.interceptor.KeyGenerator;
|
||||
import org.springframework.cache.support.SimpleCacheManager;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
@EnableCaching
|
||||
@Configuration
|
||||
public class ApplicationCacheConfig {
|
||||
|
||||
@Bean
|
||||
public CacheManager cacheManager() {
|
||||
SimpleCacheManager cacheManager = new SimpleCacheManager();
|
||||
Cache booksCache = new ConcurrentMapCache("books");
|
||||
cacheManager.setCaches(Arrays.asList(booksCache));
|
||||
return cacheManager;
|
||||
}
|
||||
|
||||
@Bean("customKeyGenerator")
|
||||
public KeyGenerator keyGenerator() {
|
||||
return new CustomKeyGenerator();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.caching.config;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.cache.concurrent.ConcurrentMapCache;
|
||||
import org.springframework.cache.support.SimpleCacheManager;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@EnableCaching
|
||||
@ComponentScan("com.baeldung.caching.example")
|
||||
public class CachingConfig {
|
||||
|
||||
@Bean
|
||||
public CacheManager cacheManager() {
|
||||
final SimpleCacheManager cacheManager = new SimpleCacheManager();
|
||||
cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("directory"), new ConcurrentMapCache("addresses")));
|
||||
return cacheManager;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.caching.config;
|
||||
|
||||
import org.springframework.cache.interceptor.KeyGenerator;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
public class CustomKeyGenerator implements KeyGenerator {
|
||||
|
||||
public Object generate(Object target, Method method, Object... params) {
|
||||
return target.getClass().getSimpleName() + "_" + method.getName() + "_"
|
||||
+ StringUtils.arrayToDelimitedString(params, "_");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.caching.eviction.controllers;
|
||||
|
||||
import com.baeldung.caching.eviction.service.CachingService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class CachingController {
|
||||
|
||||
@Autowired
|
||||
CachingService cachingService;
|
||||
|
||||
@GetMapping("clearAllCaches")
|
||||
public void clearAllCaches() {
|
||||
cachingService.evictAllCaches();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.caching.eviction.service;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class CachingService {
|
||||
|
||||
@Autowired
|
||||
CacheManager cacheManager;
|
||||
|
||||
public void putToCache(String cacheName, String key, String value) {
|
||||
cacheManager.getCache(cacheName).put(key, value);
|
||||
}
|
||||
|
||||
public String getFromCache(String cacheName, String key) {
|
||||
String value = null;
|
||||
if (cacheManager.getCache(cacheName).get(key) != null) {
|
||||
value = cacheManager.getCache(cacheName).get(key).get().toString();
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
@CacheEvict(value = "first", key = "#cacheKey")
|
||||
public void evictSingleCacheValue(String cacheKey) {
|
||||
}
|
||||
|
||||
@CacheEvict(value = "first", allEntries = true)
|
||||
public void evictAllCacheValues() {
|
||||
}
|
||||
|
||||
public void evictSingleCacheValue(String cacheName, String cacheKey) {
|
||||
cacheManager.getCache(cacheName).evict(cacheKey);
|
||||
}
|
||||
|
||||
public void evictAllCacheValues(String cacheName) {
|
||||
cacheManager.getCache(cacheName).clear();
|
||||
}
|
||||
|
||||
public void evictAllCaches() {
|
||||
cacheManager.getCacheNames()
|
||||
.parallelStream()
|
||||
.forEach(cacheName -> cacheManager.getCache(cacheName).clear());
|
||||
}
|
||||
|
||||
@Scheduled(fixedRate = 6000)
|
||||
public void evictAllcachesAtIntervals() {
|
||||
evictAllCaches();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.baeldung.caching.example;
|
||||
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.CachePut;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.cache.annotation.Caching;
|
||||
|
||||
public abstract class AbstractService {
|
||||
|
||||
// this method configuration is equivalent to xml configuration
|
||||
@Cacheable(value = "addresses", key = "#customer.name")
|
||||
public String getAddress(final Customer customer) {
|
||||
return customer.getAddress();
|
||||
}
|
||||
|
||||
/**
|
||||
* The method returns the customer's address,
|
||||
only it doesn't find it the cache- addresses and directory.
|
||||
*
|
||||
* @param customer the customer
|
||||
* @return the address
|
||||
*/
|
||||
@Cacheable({ "addresses", "directory" })
|
||||
public String getAddress1(final Customer customer) {
|
||||
return customer.getAddress();
|
||||
}
|
||||
|
||||
/**
|
||||
* The method returns the customer's address,
|
||||
but refreshes all the entries in the cache to load new ones.
|
||||
*
|
||||
* @param customer the customer
|
||||
* @return the address
|
||||
*/
|
||||
@CacheEvict(value = "addresses", allEntries = true)
|
||||
public String getAddress2(final Customer customer) {
|
||||
return customer.getAddress();
|
||||
}
|
||||
|
||||
/**
|
||||
* The method returns the customer's address,
|
||||
but not before selectively evicting the cache as per specified paramters.
|
||||
*
|
||||
* @param customer the customer
|
||||
* @return the address
|
||||
*/
|
||||
@Caching(evict = { @CacheEvict("addresses"), @CacheEvict(value = "directory", key = "#customer.name") })
|
||||
public String getAddress3(final Customer customer) {
|
||||
return customer.getAddress();
|
||||
}
|
||||
|
||||
/**
|
||||
* The method uses the class level cache to look up for entries.
|
||||
*
|
||||
* @param customer the customer
|
||||
* @return the address
|
||||
*/
|
||||
@Cacheable
|
||||
// parameter not required as we have declared it using @CacheConfig
|
||||
public String getAddress4(final Customer customer) {
|
||||
return customer.getAddress();
|
||||
}
|
||||
|
||||
/**
|
||||
* The method selectively caches the results that meet the predefined criteria.
|
||||
*
|
||||
* @param customer the customer
|
||||
* @return the address
|
||||
*/
|
||||
@CachePut(value = "addresses", condition = "#customer.name=='Tom'")
|
||||
// @CachePut(value = "addresses", unless = "#result.length>64")
|
||||
public String getAddress5(final Customer customer) {
|
||||
return customer.getAddress();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.caching.example;
|
||||
|
||||
import com.baeldung.caching.model.Book;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
public class BookService {
|
||||
|
||||
@Cacheable(value="books", keyGenerator="customKeyGenerator")
|
||||
public List<Book> getBooks() {
|
||||
List<Book> books = new ArrayList<Book>();
|
||||
books.add(new Book(1, "The Counterfeiters", "André Gide"));
|
||||
books.add(new Book(2, "Peer Gynt and Hedda Gabler", "Henrik Ibsen"));
|
||||
return books;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.caching.example;
|
||||
|
||||
public class Customer {
|
||||
|
||||
private int id;
|
||||
private String name;
|
||||
private String address;
|
||||
|
||||
public Customer() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Customer(final String name, final String address) {
|
||||
this.name = name;
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(final String address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public void setCustomerAddress(final String address) {
|
||||
this.address = name + "," + address;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.baeldung.caching.example;
|
||||
|
||||
import org.springframework.cache.annotation.CacheConfig;
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.CachePut;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.cache.annotation.Caching;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@CacheConfig(cacheNames = { "addresses" })
|
||||
public class CustomerDataService {
|
||||
|
||||
// this method configuration is equivalent to xml configuration
|
||||
@Cacheable(value = "addresses", key = "#customer.name")
|
||||
public String getAddress(final Customer customer) {
|
||||
return customer.getAddress();
|
||||
}
|
||||
|
||||
/**
|
||||
* The method returns the customer's address,
|
||||
only it doesn't find it the cache- addresses and directory.
|
||||
*
|
||||
* @param customer the customer
|
||||
* @return the address
|
||||
*/
|
||||
@Cacheable({ "addresses", "directory" })
|
||||
public String getAddress1(final Customer customer) {
|
||||
return customer.getAddress();
|
||||
}
|
||||
|
||||
/**
|
||||
* The method returns the customer's address,
|
||||
but refreshes all the entries in the cache to load new ones.
|
||||
*
|
||||
* @param customer the customer
|
||||
* @return the address
|
||||
*/
|
||||
@CacheEvict(value = "addresses", allEntries = true)
|
||||
public String getAddress2(final Customer customer) {
|
||||
return customer.getAddress();
|
||||
}
|
||||
|
||||
/**
|
||||
* The method returns the customer's address,
|
||||
but not before selectively evicting the cache as per specified paramters.
|
||||
*
|
||||
* @param customer the customer
|
||||
* @return the address
|
||||
*/
|
||||
@Caching(evict = { @CacheEvict("addresses"), @CacheEvict(value = "directory", key = "#customer.name") })
|
||||
public String getAddress3(final Customer customer) {
|
||||
return customer.getAddress();
|
||||
}
|
||||
|
||||
/**
|
||||
* The method uses the class level cache to look up for entries.
|
||||
*
|
||||
* @param customer the customer
|
||||
* @return the address
|
||||
*/
|
||||
@Cacheable
|
||||
// parameter not required as we have declared it using @CacheConfig
|
||||
public String getAddress4(final Customer customer) {
|
||||
return customer.getAddress();
|
||||
}
|
||||
|
||||
/**
|
||||
* The method selectively caches the results that meet the predefined criteria.
|
||||
*
|
||||
* @param customer the customer
|
||||
* @return the address
|
||||
*/
|
||||
@CachePut(value = "addresses", condition = "#customer.name=='Tom'")
|
||||
// @CachePut(value = "addresses", unless = "#result.length>64")
|
||||
public String getAddress5(final Customer customer) {
|
||||
return customer.getAddress();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.caching.example;
|
||||
|
||||
import org.springframework.cache.annotation.CacheConfig;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@CacheConfig(cacheNames = { "addresses" })
|
||||
public class CustomerServiceWithParent extends AbstractService {
|
||||
//
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.caching.model;
|
||||
|
||||
public class Book {
|
||||
|
||||
private int id;
|
||||
private String author;
|
||||
private String title;
|
||||
|
||||
public Book() {
|
||||
}
|
||||
|
||||
public Book(int id, String author, String title) {
|
||||
this.id = id;
|
||||
this.author = author;
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public void setAuthor(String author) {
|
||||
this.author = author;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.ehcache.calculator;
|
||||
|
||||
import com.baeldung.ehcache.config.CacheHelper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class SquaredCalculator {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(SquaredCalculator.class);
|
||||
private CacheHelper cache;
|
||||
|
||||
public int getSquareValueOfNumber(int input) {
|
||||
if (cache.getSquareNumberCache().containsKey(input)) {
|
||||
return cache.getSquareNumberCache().get(input);
|
||||
}
|
||||
|
||||
LOGGER.debug("Calculating square value of {} and caching result.", input);
|
||||
|
||||
int squaredValue = (int) Math.pow(input, 2);
|
||||
cache.getSquareNumberCache().put(input, squaredValue);
|
||||
|
||||
return squaredValue;
|
||||
}
|
||||
|
||||
public void setCache(CacheHelper cache) {
|
||||
this.cache = cache;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.baeldung.ehcache.config;
|
||||
|
||||
import org.ehcache.Cache;
|
||||
import org.ehcache.CacheManager;
|
||||
import org.ehcache.config.builders.CacheConfigurationBuilder;
|
||||
import org.ehcache.config.builders.CacheManagerBuilder;
|
||||
import org.ehcache.config.builders.ResourcePoolsBuilder;
|
||||
|
||||
public class CacheHelper {
|
||||
|
||||
private CacheManager cacheManager;
|
||||
private Cache<Integer, Integer> squareNumberCache;
|
||||
|
||||
public CacheHelper() {
|
||||
cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build();
|
||||
cacheManager.init();
|
||||
|
||||
squareNumberCache = cacheManager.createCache("squaredNumber", CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, Integer.class, ResourcePoolsBuilder.heap(10)));
|
||||
}
|
||||
|
||||
public Cache<Integer, Integer> getSquareNumberCache() {
|
||||
return squareNumberCache;
|
||||
}
|
||||
|
||||
public Cache<Integer, Integer> getSquareNumberCacheFromCacheManager() {
|
||||
return cacheManager.getCache("squaredNumber", Integer.class, Integer.class);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.multiplecachemanager.bo;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.baeldung.multiplecachemanager.entity.Customer;
|
||||
import com.baeldung.multiplecachemanager.entity.Order;
|
||||
import com.baeldung.multiplecachemanager.repository.CustomerDetailRepository;
|
||||
|
||||
@Component
|
||||
public class CustomerDetailBO {
|
||||
|
||||
@Autowired
|
||||
private CustomerDetailRepository customerDetailRepository;
|
||||
|
||||
@Cacheable(cacheNames = "customers")
|
||||
public Customer getCustomerDetail(Integer customerId) {
|
||||
return customerDetailRepository.getCustomerDetail(customerId);
|
||||
}
|
||||
|
||||
@Cacheable(cacheNames = "customerOrders", cacheManager = "alternateCacheManager")
|
||||
public List<Order> getCustomerOrders(Integer customerId) {
|
||||
return customerDetailRepository.getCustomerOrders(customerId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.multiplecachemanager.bo;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.baeldung.multiplecachemanager.entity.Order;
|
||||
import com.baeldung.multiplecachemanager.repository.OrderDetailRepository;
|
||||
|
||||
@Component
|
||||
public class OrderDetailBO {
|
||||
|
||||
@Autowired
|
||||
private OrderDetailRepository orderDetailRepository;
|
||||
|
||||
@Cacheable(cacheNames = "orders", cacheResolver = "cacheResolver")
|
||||
public Order getOrderDetail(Integer orderId) {
|
||||
return orderDetailRepository.getOrderDetail(orderId);
|
||||
}
|
||||
|
||||
@Cacheable(cacheNames = "orderprice", cacheResolver = "cacheResolver")
|
||||
public double getOrderPrice(Integer orderId) {
|
||||
return orderDetailRepository.getOrderPrice(orderId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.multiplecachemanager.config;
|
||||
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.annotation.CachingConfigurerSupport;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.cache.caffeine.CaffeineCacheManager;
|
||||
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
|
||||
import org.springframework.cache.interceptor.CacheResolver;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
//import org.springframework.context.annotation.Primary;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
|
||||
@Configuration
|
||||
@EnableCaching
|
||||
public class MultipleCacheManagerConfig extends CachingConfigurerSupport {
|
||||
|
||||
@Bean
|
||||
//@Primary
|
||||
public CacheManager cacheManager() {
|
||||
CaffeineCacheManager cacheManager = new CaffeineCacheManager("customers", "orders");
|
||||
cacheManager.setCaffeine(Caffeine.newBuilder()
|
||||
.initialCapacity(200)
|
||||
.maximumSize(500)
|
||||
.weakKeys()
|
||||
.recordStats());
|
||||
return cacheManager;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CacheManager alternateCacheManager() {
|
||||
return new ConcurrentMapCacheManager("customerOrders", "orderprice");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CacheResolver cacheResolver() {
|
||||
return new MultipleCacheResolver(alternateCacheManager(), cacheManager());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.multiplecachemanager.config;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.interceptor.CacheOperationInvocationContext;
|
||||
import org.springframework.cache.interceptor.CacheResolver;
|
||||
|
||||
public class MultipleCacheResolver implements CacheResolver {
|
||||
|
||||
private final CacheManager simpleCacheManager;
|
||||
|
||||
private final CacheManager caffeineCacheManager;
|
||||
|
||||
private static final String ORDER_CACHE = "orders";
|
||||
|
||||
private static final String ORDER_PRICE_CACHE = "orderprice";
|
||||
|
||||
public MultipleCacheResolver(CacheManager simpleCacheManager, CacheManager caffeineCacheManager) {
|
||||
this.simpleCacheManager = simpleCacheManager;
|
||||
this.caffeineCacheManager = caffeineCacheManager;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<? extends Cache> resolveCaches(CacheOperationInvocationContext<?> context) {
|
||||
Collection<Cache> caches = new ArrayList<Cache>();
|
||||
if ("getOrderDetail".equals(context.getMethod()
|
||||
.getName())) {
|
||||
caches.add(caffeineCacheManager.getCache(ORDER_CACHE));
|
||||
} else {
|
||||
caches.add(simpleCacheManager.getCache(ORDER_PRICE_CACHE));
|
||||
}
|
||||
return caches;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.multiplecachemanager.controller;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.multiplecachemanager.bo.CustomerDetailBO;
|
||||
import com.baeldung.multiplecachemanager.bo.OrderDetailBO;
|
||||
import com.baeldung.multiplecachemanager.entity.Customer;
|
||||
import com.baeldung.multiplecachemanager.entity.Order;
|
||||
|
||||
@RestController
|
||||
public class MultipleCacheManagerController {
|
||||
|
||||
@Autowired
|
||||
private CustomerDetailBO customerDetailBO;
|
||||
|
||||
@Autowired
|
||||
private OrderDetailBO orderDetailBO;
|
||||
|
||||
@GetMapping(value = "/getCustomer/{customerid}")
|
||||
public Customer getCustomer(@PathVariable Integer customerid) {
|
||||
return customerDetailBO.getCustomerDetail(customerid);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/getCustomerOrders/{customerid}")
|
||||
public List<Order> getCustomerOrders(@PathVariable Integer customerid) {
|
||||
return customerDetailBO.getCustomerOrders(customerid);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/getOrder/{orderid}")
|
||||
public Order getOrder(@PathVariable Integer orderid) {
|
||||
return orderDetailBO.getOrderDetail(orderid);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/getOrderPrice/{orderid}")
|
||||
public double getOrderPrice(@PathVariable Integer orderid) {
|
||||
return orderDetailBO.getOrderPrice(orderid);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.multiplecachemanager.entity;
|
||||
|
||||
public class Customer {
|
||||
|
||||
private int customerId;
|
||||
|
||||
private String customerName;
|
||||
|
||||
public int getCustomerId() {
|
||||
return customerId;
|
||||
}
|
||||
|
||||
public void setCustomerId(int customerId) {
|
||||
this.customerId = customerId;
|
||||
}
|
||||
|
||||
public String getCustomerName() {
|
||||
return customerName;
|
||||
}
|
||||
|
||||
public void setCustomerName(String customerName) {
|
||||
this.customerName = customerName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.multiplecachemanager.entity;
|
||||
|
||||
public class Item {
|
||||
|
||||
private int itemId;
|
||||
|
||||
private String itemDesc;
|
||||
|
||||
private double itemPrice;
|
||||
|
||||
public int getItemId() {
|
||||
return itemId;
|
||||
}
|
||||
|
||||
public void setItemId(int itemId) {
|
||||
this.itemId = itemId;
|
||||
}
|
||||
|
||||
public String getItemDesc() {
|
||||
return itemDesc;
|
||||
}
|
||||
|
||||
public void setItemDesc(String itemDesc) {
|
||||
this.itemDesc = itemDesc;
|
||||
}
|
||||
|
||||
public double getItemPrice() {
|
||||
return itemPrice;
|
||||
}
|
||||
|
||||
public void setItemPrice(double itemPrice) {
|
||||
this.itemPrice = itemPrice;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.multiplecachemanager.entity;
|
||||
|
||||
public class Order {
|
||||
|
||||
private int orderId;
|
||||
|
||||
private int itemId;
|
||||
|
||||
private int quantity;
|
||||
|
||||
private int customerId;
|
||||
|
||||
public int getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public void setOrderId(int orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
|
||||
public int getItemId() {
|
||||
return itemId;
|
||||
}
|
||||
|
||||
public void setItemId(int itemId) {
|
||||
this.itemId = itemId;
|
||||
}
|
||||
|
||||
public int getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
public void setQuantity(int quantity) {
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
public int getCustomerId() {
|
||||
return customerId;
|
||||
}
|
||||
|
||||
public void setCustomerId(int customerId) {
|
||||
this.customerId = customerId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.multiplecachemanager.repository;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.RowCallbackHandler;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.baeldung.multiplecachemanager.entity.Customer;
|
||||
import com.baeldung.multiplecachemanager.entity.Order;
|
||||
|
||||
@Repository
|
||||
public class CustomerDetailRepository {
|
||||
|
||||
@Autowired
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
|
||||
public Customer getCustomerDetail(Integer customerId) {
|
||||
String customerQuery = "select * from customer where customerid = ? ";
|
||||
Customer customer = new Customer();
|
||||
jdbcTemplate.query(customerQuery, new Object[] { customerId }, new RowCallbackHandler() {
|
||||
public void processRow(ResultSet rs) throws SQLException {
|
||||
customer.setCustomerId(rs.getInt("customerid"));
|
||||
customer.setCustomerName(rs.getString("customername"));
|
||||
}
|
||||
});
|
||||
return customer;
|
||||
}
|
||||
|
||||
public List<Order> getCustomerOrders(Integer customerId) {
|
||||
String customerOrderQuery = "select * from orderdetail where customerid = ? ";
|
||||
List<Order> orders = new ArrayList<Order>();
|
||||
jdbcTemplate.query(customerOrderQuery, new Object[] { customerId }, new RowCallbackHandler() {
|
||||
public void processRow(ResultSet rs) throws SQLException {
|
||||
Order order = new Order();
|
||||
order.setCustomerId(rs.getInt("customerid"));
|
||||
order.setItemId(rs.getInt("orderid"));
|
||||
order.setOrderId(rs.getInt("orderid"));
|
||||
order.setQuantity(rs.getInt("quantity"));
|
||||
orders.add(order);
|
||||
}
|
||||
});
|
||||
return orders;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.multiplecachemanager.repository;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.RowCallbackHandler;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.baeldung.multiplecachemanager.entity.Item;
|
||||
import com.baeldung.multiplecachemanager.entity.Order;
|
||||
|
||||
@Repository
|
||||
public class OrderDetailRepository {
|
||||
|
||||
@Autowired
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
|
||||
public Order getOrderDetail(Integer orderId) {
|
||||
String orderDetailQuery = "select * from orderdetail where orderid = ? ";
|
||||
Order order = new Order();
|
||||
jdbcTemplate.query(orderDetailQuery, new Object[] { orderId }, new RowCallbackHandler() {
|
||||
public void processRow(ResultSet rs) throws SQLException {
|
||||
order.setCustomerId(rs.getInt("customerid"));
|
||||
order.setOrderId(rs.getInt("orderid"));
|
||||
order.setItemId(rs.getInt("itemid"));
|
||||
order.setQuantity(rs.getInt("quantity"));
|
||||
}
|
||||
});
|
||||
return order;
|
||||
}
|
||||
|
||||
public double getOrderPrice(Integer orderId) {
|
||||
|
||||
String orderItemJoinQuery = "select * from ( select * from orderdetail where orderid = ? ) o left join item on o.itemid = ITEM.itemid";
|
||||
Order order = new Order();
|
||||
Item item = new Item();
|
||||
|
||||
jdbcTemplate.query(orderItemJoinQuery, new Object[] { orderId }, new RowCallbackHandler() {
|
||||
public void processRow(ResultSet rs) throws SQLException {
|
||||
order.setCustomerId(rs.getInt("customerid"));
|
||||
order.setOrderId(rs.getInt("orderid"));
|
||||
order.setItemId(rs.getInt("itemid"));
|
||||
order.setQuantity(rs.getInt("quantity"));
|
||||
item.setItemDesc("itemdesc");
|
||||
item.setItemId(rs.getInt("itemid"));
|
||||
item.setItemPrice(rs.getDouble("price"));
|
||||
}
|
||||
});
|
||||
return order.getQuantity() * item.getItemPrice();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.springdatacaching.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.UUID;
|
||||
|
||||
@Data
|
||||
@Entity
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class Book implements Serializable {
|
||||
|
||||
@Id
|
||||
private UUID id;
|
||||
private String title;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.springdatacaching.repositories;
|
||||
|
||||
import com.baeldung.springdatacaching.model.Book;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface BookRepository extends CrudRepository<Book, UUID> {
|
||||
|
||||
@Cacheable(value = "books", unless = "#a0=='Foundation'")
|
||||
Optional<Book> findFirstByTitle(String title);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE
|
||||
spring.datasource.driverClassName=org.h2.Driver
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=
|
||||
|
||||
# Enabling H2 Console
|
||||
spring.h2.console.enabled=true
|
||||
spring.h2.console.path=/h2
|
||||
|
||||
#ehcache
|
||||
spring.cache.jcache.config=classpath:ehcache.xml
|
||||
@@ -0,0 +1,40 @@
|
||||
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cache="http://www.springframework.org/schema/cache"
|
||||
xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
|
||||
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.2.xsd
|
||||
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
|
||||
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
|
||||
"
|
||||
>
|
||||
|
||||
<cache:annotation-driven/>
|
||||
|
||||
<!-- <context:annotation-config/> -->
|
||||
|
||||
<!-- the service that you wish to make cacheable. -->
|
||||
<bean id="customerDataService" class="com.baeldung.caching.example.CustomerDataService"/>
|
||||
|
||||
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
|
||||
<property name="caches">
|
||||
<set>
|
||||
<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" name="directory"/>
|
||||
<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" name="addresses"/>
|
||||
</set>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
<!-- define caching behavior -->
|
||||
<cache:advice id="cachingBehavior" cache-manager="cacheManager">
|
||||
<cache:caching cache="addresses">
|
||||
<cache:cacheable method="getAddress" key="#customer.name"/>
|
||||
</cache:caching>
|
||||
</cache:advice>
|
||||
|
||||
|
||||
<!-- apply the behavior to all the implementations of CustomerDataService -->
|
||||
<aop:config>
|
||||
<aop:advisor advice-ref="cachingBehavior" pointcut="execution(* com.baeldung.caching.example.CustomerDataService.*(..))"/>
|
||||
</aop:config>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,7 @@
|
||||
INSERT INTO CUSTOMER VALUES(1001,'BAELDUNG');
|
||||
|
||||
INSERT INTO ITEM VALUES(10001,'ITEM1',50.0);
|
||||
INSERT INTO ITEM VALUES(10002,'ITEM2',100.0);
|
||||
|
||||
INSERT INTO ORDERDETAIL VALUES(300001,1001,10001,2);
|
||||
INSERT INTO ORDERDETAIL VALUES(300002,1001,10002,5);
|
||||
@@ -0,0 +1,54 @@
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://www.ehcache.org/v3"
|
||||
xmlns:jsr107="http://www.ehcache.org/v3/jsr107"
|
||||
xsi:schemaLocation="
|
||||
http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd
|
||||
http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">
|
||||
|
||||
<cache alias="squareCache">
|
||||
<key-type>java.lang.Long</key-type>
|
||||
<value-type>java.math.BigDecimal</value-type>
|
||||
<expiry>
|
||||
<ttl unit="seconds">30</ttl>
|
||||
</expiry>
|
||||
|
||||
<listeners>
|
||||
<listener>
|
||||
<class>com.baeldung.cachetest.config.CacheEventLogger</class>
|
||||
<event-firing-mode>ASYNCHRONOUS</event-firing-mode>
|
||||
<event-ordering-mode>UNORDERED</event-ordering-mode>
|
||||
<events-to-fire-on>CREATED</events-to-fire-on>
|
||||
<events-to-fire-on>EXPIRED</events-to-fire-on>
|
||||
</listener>
|
||||
</listeners>
|
||||
|
||||
<resources>
|
||||
<heap unit="entries">2</heap>
|
||||
<offheap unit="MB">10</offheap>
|
||||
</resources>
|
||||
</cache>
|
||||
|
||||
<cache alias="books">
|
||||
<key-type>java.lang.String</key-type>
|
||||
<value-type>com.baeldung.springdatacaching.model.Book</value-type>
|
||||
<expiry>
|
||||
<ttl unit="seconds">30</ttl>
|
||||
</expiry>
|
||||
|
||||
<listeners>
|
||||
<listener>
|
||||
<class>com.baeldung.cachetest.config.CacheEventLogger</class>
|
||||
<event-firing-mode>ASYNCHRONOUS</event-firing-mode>
|
||||
<event-ordering-mode>UNORDERED</event-ordering-mode>
|
||||
<events-to-fire-on>CREATED</events-to-fire-on>
|
||||
<events-to-fire-on>EXPIRED</events-to-fire-on>
|
||||
</listener>
|
||||
</listeners>
|
||||
|
||||
<resources>
|
||||
<heap unit="entries">2</heap>
|
||||
<offheap unit="MB">10</offheap>
|
||||
</resources>
|
||||
</cache>
|
||||
|
||||
</config>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,23 @@
|
||||
DROP TABLE ORDERDETAIL IF EXISTS;
|
||||
DROP TABLE ITEM IF EXISTS;
|
||||
DROP TABLE CUSTOMER IF EXISTS;
|
||||
|
||||
CREATE TABLE CUSTOMER(
|
||||
CUSTOMERID INT PRIMARY KEY,
|
||||
CUSTOMERNAME VARCHAR(250) NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE ITEM(
|
||||
ITEMID INT PRIMARY KEY,
|
||||
ITEMDESC VARCHAR(250),
|
||||
PRICE DOUBLE
|
||||
);
|
||||
|
||||
CREATE TABLE ORDERDETAIL(
|
||||
ORDERID INT PRIMARY KEY,
|
||||
CUSTOMERID INT NOT NULL,
|
||||
ITEMID INT NOT NULL,
|
||||
QUANTITY INT,
|
||||
FOREIGN KEY (customerid) references CUSTOMER(customerid),
|
||||
FOREIGN KEY (itemid) references ITEM(itemid)
|
||||
);
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.caching.boot;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest("spring.cache.type=simple")
|
||||
public class SimpleCacheCustomizerIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private CacheManager cacheManager;
|
||||
|
||||
@Test
|
||||
public void givenCacheManagerCustomizerWhenBootstrappedThenCacheManagerCustomized() {
|
||||
assertThat(cacheManager.getCacheNames())
|
||||
.containsOnly(SimpleCacheCustomizer.USERS_CACHE, SimpleCacheCustomizer.TRANSACTIONS_CACHE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.baeldung.caching.test;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.hamcrest.CoreMatchers.nullValue;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.caching.eviction.service.CachingService;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean;
|
||||
import org.springframework.cache.support.SimpleCacheManager;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration
|
||||
public class CacheEvictAnnotationIntegrationTest {
|
||||
|
||||
@Configuration
|
||||
@EnableCaching
|
||||
static class ContextConfiguration {
|
||||
|
||||
@Bean
|
||||
public CachingService cachingService() {
|
||||
return new CachingService();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CacheManager cacheManager() {
|
||||
SimpleCacheManager cacheManager = new SimpleCacheManager();
|
||||
List<Cache> caches = new ArrayList<>();
|
||||
caches.add(cacheBean().getObject());
|
||||
cacheManager.setCaches(caches);
|
||||
return cacheManager;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ConcurrentMapCacheFactoryBean cacheBean() {
|
||||
ConcurrentMapCacheFactoryBean cacheFactoryBean = new ConcurrentMapCacheFactoryBean();
|
||||
cacheFactoryBean.setName("first");
|
||||
return cacheFactoryBean;
|
||||
}
|
||||
}
|
||||
|
||||
@Autowired
|
||||
CachingService cachingService;
|
||||
|
||||
@Before
|
||||
public void before() {
|
||||
cachingService.putToCache("first", "key1", "Baeldung");
|
||||
cachingService.putToCache("first", "key2", "Article");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFirstCache_whenSingleCacheValueEvictRequested_thenEmptyCacheValue() {
|
||||
cachingService.evictSingleCacheValue("key1");
|
||||
String key1 = cachingService.getFromCache("first", "key1");
|
||||
assertThat(key1, is(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFirstCache_whenAllCacheValueEvictRequested_thenEmptyCache() {
|
||||
cachingService.evictAllCacheValues();
|
||||
String key1 = cachingService.getFromCache("first", "key1");
|
||||
String key2 = cachingService.getFromCache("first", "key2");
|
||||
assertThat(key1, is(nullValue()));
|
||||
assertThat(key2, is(nullValue()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.baeldung.caching.test;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.hamcrest.CoreMatchers.nullValue;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.caching.eviction.service.CachingService;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean;
|
||||
import org.springframework.cache.support.SimpleCacheManager;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration
|
||||
public class CacheManagerEvictIntegrationTest {
|
||||
|
||||
@Configuration
|
||||
static class ContextConfiguration {
|
||||
|
||||
@Bean
|
||||
public CachingService cachingService() {
|
||||
return new CachingService();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CacheManager cacheManager() {
|
||||
SimpleCacheManager cacheManager = new SimpleCacheManager();
|
||||
List<Cache> caches = new ArrayList<>();
|
||||
caches.add(cacheBeanFirst().getObject());
|
||||
caches.add(cacheBeanSecond().getObject());
|
||||
cacheManager.setCaches(caches);
|
||||
return cacheManager;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ConcurrentMapCacheFactoryBean cacheBeanFirst() {
|
||||
ConcurrentMapCacheFactoryBean cacheFactoryBean = new ConcurrentMapCacheFactoryBean();
|
||||
cacheFactoryBean.setName("first");
|
||||
return cacheFactoryBean;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ConcurrentMapCacheFactoryBean cacheBeanSecond() {
|
||||
ConcurrentMapCacheFactoryBean cacheFactoryBean = new ConcurrentMapCacheFactoryBean();
|
||||
cacheFactoryBean.setName("second");
|
||||
return cacheFactoryBean;
|
||||
}
|
||||
}
|
||||
|
||||
@Autowired
|
||||
CachingService cachingService;
|
||||
|
||||
@Before
|
||||
public void before() {
|
||||
cachingService.putToCache("first", "key1", "Baeldung");
|
||||
cachingService.putToCache("first", "key2", "Article");
|
||||
cachingService.putToCache("second", "key", "Article");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFirstCache_whenSingleCacheValueEvictRequested_thenEmptyCacheValue() {
|
||||
cachingService.evictSingleCacheValue("first", "key1");
|
||||
String key1 = cachingService.getFromCache("first", "key1");
|
||||
assertThat(key1, is(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFirstCache_whenAllCacheValueEvictRequested_thenEmptyCache() {
|
||||
cachingService.evictAllCacheValues("first");
|
||||
String key1 = cachingService.getFromCache("first", "key1");
|
||||
String key2 = cachingService.getFromCache("first", "key2");
|
||||
assertThat(key1, is(nullValue()));
|
||||
assertThat(key2, is(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAllCaches_whenAllCacheEvictRequested_thenEmptyAllCaches() {
|
||||
cachingService.evictAllCaches();
|
||||
String key1 = cachingService.getFromCache("first", "key1");
|
||||
assertThat(key1, is(nullValue()));
|
||||
|
||||
String key = cachingService.getFromCache("second", "key");
|
||||
assertThat(key, is(nullValue()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.baeldung.caching.test;
|
||||
|
||||
import com.baeldung.caching.config.CachingConfig;
|
||||
import com.baeldung.caching.example.Customer;
|
||||
import com.baeldung.caching.example.CustomerDataService;
|
||||
import com.baeldung.caching.example.CustomerServiceWithParent;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { CachingConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
public class SpringCachingIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private CustomerDataService service;
|
||||
|
||||
@Autowired
|
||||
private CustomerServiceWithParent serviceWithParent;
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
public void whenGettingAddress_thenCorrect() {
|
||||
final Customer cust = new Customer("Tom", "67-2, Downing Street, NY");
|
||||
service.getAddress(cust);
|
||||
service.getAddress(cust);
|
||||
|
||||
service.getAddress1(cust);
|
||||
service.getAddress1(cust);
|
||||
|
||||
service.getAddress2(cust);
|
||||
service.getAddress2(cust);
|
||||
|
||||
service.getAddress3(cust);
|
||||
service.getAddress3(cust);
|
||||
|
||||
service.getAddress4(cust);
|
||||
service.getAddress4(cust);
|
||||
|
||||
service.getAddress5(cust);
|
||||
service.getAddress5(cust);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUsingServiceWithParent_whenGettingAddress_thenCorrect() {
|
||||
final Customer cust = new Customer("Tom", "67-2, Downing Street, NY");
|
||||
|
||||
serviceWithParent.getAddress(cust);
|
||||
serviceWithParent.getAddress(cust);
|
||||
|
||||
serviceWithParent.getAddress1(cust);
|
||||
serviceWithParent.getAddress1(cust);
|
||||
|
||||
serviceWithParent.getAddress2(cust);
|
||||
serviceWithParent.getAddress2(cust);
|
||||
|
||||
serviceWithParent.getAddress3(cust);
|
||||
serviceWithParent.getAddress3(cust);
|
||||
|
||||
// serviceWithParent.getAddress4(cust);
|
||||
// serviceWithParent.getAddress4(cust);
|
||||
|
||||
serviceWithParent.getAddress5(cust);
|
||||
serviceWithParent.getAddress5(cust);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.ehcache;
|
||||
|
||||
import com.baeldung.ehcache.calculator.SquaredCalculator;
|
||||
import com.baeldung.ehcache.config.CacheHelper;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class SquareCalculatorUnitTest {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(SquareCalculatorUnitTest.class);
|
||||
|
||||
private final SquaredCalculator squaredCalculator = new SquaredCalculator();
|
||||
private final CacheHelper cacheHelper = new CacheHelper();
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
squaredCalculator.setCache(cacheHelper);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingSquareValueOnce_thenCacheDontHaveValues() {
|
||||
for (int i = 10; i < 15; i++) {
|
||||
assertFalse(cacheHelper.getSquareNumberCache().containsKey(i));
|
||||
LOGGER.debug("Square value of {} is: {}", i, squaredCalculator.getSquareValueOfNumber(i));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCalculatingSquareValueAgain_thenCacheHasAllValues() {
|
||||
for (int i = 10; i < 15; i++) {
|
||||
assertFalse(cacheHelper.getSquareNumberCache().containsKey(i));
|
||||
LOGGER.debug("Square value of {} is: {}", i, squaredCalculator.getSquareValueOfNumber(i));
|
||||
}
|
||||
|
||||
for (int i = 10; i < 15; i++) {
|
||||
assertTrue(cacheHelper.getSquareNumberCache().containsKey(i));
|
||||
LOGGER.debug("Square value of {} is: {}", i, squaredCalculator.getSquareValueOfNumber(i) + "\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.baeldung.multiplecachemanager;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.caffeine.CaffeineCache;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import com.baeldung.multiplecachemanager.bo.OrderDetailBO;
|
||||
import com.baeldung.multiplecachemanager.entity.Order;
|
||||
import com.baeldung.multiplecachemanager.repository.OrderDetailRepository;
|
||||
|
||||
@SpringBootApplication
|
||||
@SpringBootTest
|
||||
public class MultipleCacheManagerIntegrationTest {
|
||||
|
||||
@MockBean
|
||||
private OrderDetailRepository orderDetailRepository;
|
||||
|
||||
@Autowired
|
||||
private OrderDetailBO orderDetailBO;
|
||||
|
||||
@Autowired
|
||||
private CacheManager cacheManager;
|
||||
|
||||
@Autowired
|
||||
private CacheManager alternateCacheManager;
|
||||
|
||||
@Test
|
||||
public void givenCacheResolverIsConfigured_whenCallGetOrderDetail_thenDataShouldBeInCaffieneCacheManager() {
|
||||
Integer key = 30001;
|
||||
cacheManager.getCache("orders")
|
||||
.evict(key);
|
||||
Order order = new Order();
|
||||
order.setCustomerId(1001);
|
||||
order.setItemId(10001);
|
||||
order.setOrderId(30001);
|
||||
order.setQuantity(2);
|
||||
Mockito.when(orderDetailRepository.getOrderDetail(key))
|
||||
.thenReturn(order);
|
||||
orderDetailBO.getOrderDetail(key);
|
||||
org.springframework.cache.caffeine.CaffeineCache cache = (CaffeineCache) cacheManager.getCache("orders");
|
||||
Assert.notNull(cache.get(key)
|
||||
.get(), "caffieneCache should have had the data");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCacheResolverIsConfigured_whenCallGetOrderPrice_thenDataShouldBeInAlternateCacheManager() {
|
||||
Integer key = 30001;
|
||||
alternateCacheManager.getCache("orderprice")
|
||||
.evict(key);
|
||||
Mockito.when(orderDetailRepository.getOrderPrice(key))
|
||||
.thenReturn(500.0);
|
||||
orderDetailBO.getOrderPrice(key);
|
||||
Cache cache = alternateCacheManager.getCache("orderprice");
|
||||
Assert.notNull(cache.get(key)
|
||||
.get(), "alternateCache should have had the data");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.baeldung.springdatacaching.repositories;
|
||||
|
||||
import com.baeldung.springdatacaching.model.Book;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
import org.springframework.test.util.AopTestUtils;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static java.util.Optional.of;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ContextConfiguration
|
||||
@ExtendWith(SpringExtension.class)
|
||||
public class BookRepositoryCachingIntegrationTest {
|
||||
|
||||
private static final Book DUNE = new Book(UUID.randomUUID(), "Dune");
|
||||
private static final Book FOUNDATION = new Book(UUID.randomUUID(), "Foundation");
|
||||
|
||||
private BookRepository mock;
|
||||
|
||||
@Autowired
|
||||
private BookRepository bookRepository;
|
||||
|
||||
@EnableCaching
|
||||
@Configuration
|
||||
public static class CachingTestConfig {
|
||||
|
||||
@Bean
|
||||
public BookRepository bookRepositoryMockImplementation() {
|
||||
return mock(BookRepository.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CacheManager cacheManager() {
|
||||
return new ConcurrentMapCacheManager("books");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mock = AopTestUtils.getTargetObject(bookRepository);
|
||||
|
||||
reset(mock);
|
||||
|
||||
when(mock.findFirstByTitle(eq("Foundation")))
|
||||
.thenReturn(of(FOUNDATION));
|
||||
|
||||
when(mock.findFirstByTitle(eq("Dune")))
|
||||
.thenReturn(of(DUNE))
|
||||
.thenThrow(new RuntimeException("Book should be cached!"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenCachedBook_whenFindByTitle_thenRepositoryShouldNotBeHit() {
|
||||
assertEquals(of(DUNE), bookRepository.findFirstByTitle("Dune"));
|
||||
verify(mock).findFirstByTitle("Dune");
|
||||
|
||||
assertEquals(of(DUNE), bookRepository.findFirstByTitle("Dune"));
|
||||
assertEquals(of(DUNE), bookRepository.findFirstByTitle("Dune"));
|
||||
|
||||
verifyNoMoreInteractions(mock);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNotCachedBook_whenFindByTitle_thenRepositoryShouldBeHit() {
|
||||
assertEquals(of(FOUNDATION), bookRepository.findFirstByTitle("Foundation"));
|
||||
assertEquals(of(FOUNDATION), bookRepository.findFirstByTitle("Foundation"));
|
||||
assertEquals(of(FOUNDATION), bookRepository.findFirstByTitle("Foundation"));
|
||||
|
||||
verify(mock, times(3)).findFirstByTitle("Foundation");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.springdatacaching.repositories;
|
||||
|
||||
import com.baeldung.caching.boot.CacheApplication;
|
||||
import com.baeldung.springdatacaching.model.Book;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.domain.EntityScan;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import static java.util.Optional.empty;
|
||||
import static java.util.Optional.ofNullable;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@ExtendWith(SpringExtension.class)
|
||||
@EntityScan(basePackageClasses = Book.class)
|
||||
@SpringBootTest(classes = CacheApplication.class)
|
||||
@EnableJpaRepositories(basePackageClasses = BookRepository.class)
|
||||
public class BookRepositoryIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
CacheManager cacheManager;
|
||||
|
||||
@Autowired
|
||||
BookRepository repository;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
repository.save(new Book(UUID.randomUUID(), "Dune"));
|
||||
repository.save(new Book(UUID.randomUUID(), "Foundation"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenBookThatShouldBeCached_whenFindByTitle_thenResultShouldBePutInCache() {
|
||||
Optional<Book> dune = repository.findFirstByTitle("Dune");
|
||||
|
||||
assertEquals(dune, getCachedBook("Dune"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenBookThatShouldNotBeCached_whenFindByTitle_thenResultShouldNotBePutInCache() {
|
||||
repository.findFirstByTitle("Foundation");
|
||||
|
||||
assertEquals(empty(), getCachedBook("Foundation"));
|
||||
}
|
||||
|
||||
private Optional<Book> getCachedBook(String title) {
|
||||
return ofNullable(cacheManager.getCache("books")).map(c -> c.get(title, Book.class));
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user