Spring cache: custom key generator (#4166)

This commit is contained in:
Felipe Santiago Corro 2018-05-05 02:40:37 -03:00 committed by maibin
parent 258d5c09f0
commit e22750ffe1
4 changed files with 76 additions and 0 deletions

View File

@ -0,0 +1,21 @@
package com.baeldung.cache;
import com.baeldung.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,14 @@
package com.baeldung.cache;
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

@ -6,6 +6,15 @@ public class Book {
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;
}

View File

@ -0,0 +1,32 @@
package com.baeldung.spring.web.config;
import com.baeldung.cache.CustomKeyGenerator;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
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 extends CachingConfigurerSupport {
@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();
}
}