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

@@ -0,0 +1,30 @@
package org.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();
}
}

View File

@@ -0,0 +1,25 @@
package org.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("org.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;
}
}

View File

@@ -0,0 +1,14 @@
package org.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, "_");
}
}

View File

@@ -0,0 +1,18 @@
package org.baeldung.caching.eviction.controllers;
import org.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();
}
}

View File

@@ -0,0 +1,53 @@
package org.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();
}
}

View File

@@ -0,0 +1,76 @@
package org.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();
}
}

View File

@@ -0,0 +1,21 @@
package org.baeldung.caching.example;
import org.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;
}
}

View File

@@ -0,0 +1,48 @@
package org.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;
}
}

View File

@@ -0,0 +1,79 @@
package org.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();
}
}

View File

@@ -0,0 +1,10 @@
package org.baeldung.caching.example;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Component;
@Component
@CacheConfig(cacheNames = { "addresses" })
public class CustomerServiceWithParent extends AbstractService {
//
}

View File

@@ -0,0 +1,41 @@
package org.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;
}
}

View File

@@ -0,0 +1,24 @@
package org.baeldung.ehcache.calculator;
import org.baeldung.ehcache.config.CacheHelper;
public class SquaredCalculator {
private CacheHelper cache;
public int getSquareValueOfNumber(int input) {
if (cache.getSquareNumberCache().containsKey(input)) {
return cache.getSquareNumberCache().get(input);
}
System.out.println("Calculating square value of " + input + " and caching result.");
int squaredValue = (int) Math.pow(input, 2);
cache.getSquareNumberCache().put(input, squaredValue);
return squaredValue;
}
public void setCache(CacheHelper cache) {
this.cache = cache;
}
}

View File

@@ -0,0 +1,29 @@
package org.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);
}
}

View File

@@ -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="org.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(* org.baeldung.caching.example.CustomerDataService.*(..))"/>
</aop:config>
</beans>