Add caching: the Spring cache abstraction, keys, eviction timing and the self-invocation trap
A Spring Boot 4.1.1 module whose test suite is the evidence for the article: 20 tests producing 22 transcripts under docs/output/, plus 12 documentation chapters. Findings the build pins: - @EnableCaching has no exposeProxy attribute; the widely-copied @EnableCaching(exposeProxy = true) does not compile. - Two methods sharing a cache name and an argument type share a key space, and one silently serves the other's answers. - The documented cache-provider detection order does not match CacheType's enum order in 4.1.1: COUCHBASE before INFINISPAN, and CACHE2K before CAFFEINE. - beforeInvocation = true is NOT deferred by TransactionAwareCacheManagerProxy on 7.0.9 - doEvict picks evictIfPresent, which the decorator does not intercept. - Four of five invalid declarations start a clean context and throw at the first call. - Caffeine on the classpath silently displaces the simple provider.
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
package com.ankurm.caching;
|
||||
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import org.springframework.aop.config.AopConfigUtils;
|
||||
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.cache.caffeine.CaffeineCacheManager;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
|
||||
import org.springframework.cache.transaction.TransactionAwareCacheManagerProxy;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
/**
|
||||
* Turns the cache annotations on.
|
||||
*
|
||||
* <p>Note what {@code @EnableCaching} does <em>not</em> accept. It has exactly three attributes
|
||||
* — {@code proxyTargetClass}, {@code mode} and {@code order} — verified with
|
||||
* {@code javap} and captured in {@code docs/output/03-enablecaching-attributes.txt}. There is no
|
||||
* {@code exposeProxy}, so the widely-copied {@code @EnableCaching(exposeProxy = true)} does not
|
||||
* compile. Turning the ThreadLocal on takes the post-processor below.
|
||||
*
|
||||
* @see <a href="../../../../../docs/03-self-invocation.md">docs/03-self-invocation.md</a>
|
||||
*/
|
||||
@Configuration
|
||||
@EnableCaching
|
||||
public class CacheConfig {
|
||||
|
||||
/**
|
||||
* Makes {@link org.springframework.aop.framework.AopContext#currentProxy()} work, which is
|
||||
* one of the three ways out of the self-invocation trap in
|
||||
* {@link com.ankurm.caching.selfinvocation.CatalogService}. {@code @EnableAspectJAutoProxy(
|
||||
* exposeProxy = true)} is the usual advice, but it pulls in AspectJ; this does the same job
|
||||
* by flipping the flag on the auto-proxy creator {@code @EnableCaching} already registered.
|
||||
*/
|
||||
@Bean
|
||||
static BeanFactoryPostProcessor exposeCachingProxy() {
|
||||
return beanFactory -> {
|
||||
if (beanFactory instanceof BeanDefinitionRegistry registry) {
|
||||
AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
|
||||
AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A Caffeine manager used only by the {@code caffeine} profile, so the TTL and size-bound
|
||||
* demonstrations have a provider that actually implements them. Without a profile the
|
||||
* application runs on Boot's auto-configured {@code simple} provider — a
|
||||
* {@code ConcurrentHashMap} with no expiry at all.
|
||||
*
|
||||
* @see <a href="../../../../../docs/08-providers-and-ttl.md">docs/08-providers-and-ttl.md</a>
|
||||
*/
|
||||
@Bean
|
||||
@Primary
|
||||
@Profile("caffeine")
|
||||
public CaffeineCacheManager caffeineCacheManager() {
|
||||
CaffeineCacheManager manager = new CaffeineCacheManager();
|
||||
manager.setCaffeine(Caffeine.newBuilder()
|
||||
.expireAfterWrite(Duration.ofMillis(400))
|
||||
.maximumSize(3)
|
||||
.recordStats());
|
||||
// Required before @Cacheable on a CompletableFuture-returning method will work.
|
||||
manager.setAsyncCacheMode(true);
|
||||
return manager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Defers every put and evict to after the transaction commits, so a rollback takes the cache
|
||||
* write with it. Reads are <em>not</em> deferred, and it only helps inside a transaction.
|
||||
*
|
||||
* @see <a href="../../../docs/10-transactions.md">docs/10-transactions.md</a>
|
||||
*/
|
||||
@Bean
|
||||
@Primary
|
||||
@Profile("txaware")
|
||||
public CacheManager transactionAwareCacheManager() {
|
||||
return new TransactionAwareCacheManagerProxy(new ConcurrentMapCacheManager());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.ankurm.caching;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
/**
|
||||
* Companion application for the ankurm.com article on the Spring cache abstraction.
|
||||
*
|
||||
* <p>Note what is <em>not</em> here: {@code @EnableCaching}. Spring Boot's reference
|
||||
* documentation explicitly advises against putting it on the main application class,
|
||||
* because that makes caching mandatory for every test slice too. It lives on
|
||||
* {@link com.ankurm.caching.CacheConfig} instead.
|
||||
*
|
||||
* @see <a href="../../../../../docs/01-what-caching-is.md">docs/01-what-caching-is.md</a>
|
||||
*/
|
||||
@SpringBootApplication
|
||||
public class CachingDemoApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(CachingDemoApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.ankurm.caching.basics;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* A value object. Records give you {@code equals} and {@code hashCode} for free, which matters
|
||||
* more than it looks: the default key generator puts method arguments straight into a hash map.
|
||||
*/
|
||||
public record Book(String isbn, String title, int year) implements Serializable {
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.ankurm.caching.basics;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* Stands in for whatever is actually slow — a database, an HTTP call, a report.
|
||||
* Every lookup sleeps and increments a counter, which is how every claim in the article
|
||||
* about "the method did not run" is measured rather than asserted.
|
||||
*
|
||||
* @see <a href="../../../../../../docs/01-what-caching-is.md">docs/01-what-caching-is.md</a>
|
||||
*/
|
||||
@Component
|
||||
public class BookRepositoryStub {
|
||||
|
||||
/** Roughly what a cold index lookup over a network costs. */
|
||||
public static final long LOOKUP_MILLIS = 200;
|
||||
|
||||
private final AtomicInteger calls = new AtomicInteger();
|
||||
|
||||
private static final Map<String, Book> DATA = Map.of(
|
||||
"978-0134685991", new Book("978-0134685991", "Effective Java", 2018),
|
||||
"978-1617294945", new Book("978-1617294945", "Spring in Action", 2022),
|
||||
"978-0596009205", new Book("978-0596009205", "Head First Design Patterns", 2004));
|
||||
|
||||
public Book load(String isbn) {
|
||||
calls.incrementAndGet();
|
||||
sleep();
|
||||
return DATA.get(isbn);
|
||||
}
|
||||
|
||||
public int callCount() {
|
||||
return calls.get();
|
||||
}
|
||||
|
||||
public void reset() {
|
||||
calls.set(0);
|
||||
}
|
||||
|
||||
private static void sleep() {
|
||||
try {
|
||||
Thread.sleep(LOOKUP_MILLIS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.ankurm.caching.basics;
|
||||
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.CachePut;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* The smallest useful caching example, and the three annotations that do 95% of the work.
|
||||
*
|
||||
* @see <a href="../../../../../../docs/02-the-three-annotations.md">docs/02-the-three-annotations.md</a>
|
||||
*/
|
||||
@Service
|
||||
public class BookService {
|
||||
|
||||
private final BookRepositoryStub repository;
|
||||
|
||||
public BookService(BookRepositoryStub repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
/** Cache {@code books}, key = the single argument, because SimpleKeyGenerator says so. */
|
||||
@Cacheable("books")
|
||||
public Book findBook(String isbn) {
|
||||
return repository.load(isbn);
|
||||
}
|
||||
|
||||
/** Always runs, then writes the result into the cache under the same key. */
|
||||
@CachePut(cacheNames = "books", key = "#book.isbn")
|
||||
public Book save(Book book) {
|
||||
return book;
|
||||
}
|
||||
|
||||
/** Removes one entry. The method body can be empty; the annotation is the point. */
|
||||
@CacheEvict(cacheNames = "books", key = "#isbn")
|
||||
public void delete(String isbn) {
|
||||
}
|
||||
|
||||
/** Clears the whole region in one operation instead of key by key. */
|
||||
@CacheEvict(cacheNames = "books", allEntries = true)
|
||||
public void reload() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.ankurm.caching.conditions;
|
||||
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* {@code condition} is evaluated before the method runs and can veto both the lookup and the
|
||||
* write. {@code unless} is evaluated after, sees {@code #result}, and can only veto the write.
|
||||
*
|
||||
* <p>Also here: what happens to {@code null}. The abstraction stores a {@code NullValue}
|
||||
* sentinel by default, so "not found" is cached like any other answer — which is usually what
|
||||
* you want for a hot miss, and occasionally exactly what you do not want.
|
||||
*
|
||||
* @see <a href="../../../../../../docs/06-conditions-and-nulls.md">docs/06-conditions-and-nulls.md</a>
|
||||
*/
|
||||
@Service
|
||||
public class LookupService {
|
||||
|
||||
private final AtomicInteger calls = new AtomicInteger();
|
||||
|
||||
/** Long search terms are one-off; caching them only evicts the useful entries. */
|
||||
@Cacheable(cacheNames = "terms", condition = "#term.length() <= 8")
|
||||
public String search(String term) {
|
||||
calls.incrementAndGet();
|
||||
return "hits-for-" + term;
|
||||
}
|
||||
|
||||
/** Cache the answer unless it is empty. */
|
||||
@Cacheable(cacheNames = "terms", unless = "#result == null")
|
||||
public String searchNullable(String term) {
|
||||
calls.incrementAndGet();
|
||||
return term.startsWith("x") ? null : "hits-for-" + term;
|
||||
}
|
||||
|
||||
/** No {@code unless}: the null is cached as NullValue and the method never runs again. */
|
||||
@Cacheable("nulls")
|
||||
public String searchCachingNulls(String term) {
|
||||
calls.incrementAndGet();
|
||||
return term.startsWith("x") ? null : "hits-for-" + term;
|
||||
}
|
||||
|
||||
public int calls() { return calls.get(); }
|
||||
public void reset() { calls.set(0); }
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package com.ankurm.caching.diag;
|
||||
|
||||
import com.ankurm.caching.basics.BookService;
|
||||
import com.ankurm.caching.conditions.LookupService;
|
||||
import com.ankurm.caching.keys.KeyShapeService;
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.concurrent.ConcurrentMapCache;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/**
|
||||
* Prints what is actually in the cache, key object by key object, with the runtime class of each
|
||||
* key. Almost every confusing caching bug becomes obvious the moment you can see the keys:
|
||||
* a {@code SimpleKey []} where you expected a string, two methods writing into one key space,
|
||||
* or a {@code NullValue} sitting where a record should be.
|
||||
*
|
||||
* <p>Delete this before shipping. It exposes cached data over HTTP with no authorisation.
|
||||
*
|
||||
* @see <a href="../../../../../../docs/11-diagnostics.md">docs/11-diagnostics.md</a>
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/diag")
|
||||
public class CacheDiagnosticsController {
|
||||
|
||||
private final CacheManager cacheManager;
|
||||
private final BookService books;
|
||||
private final KeyShapeService shapes;
|
||||
private final LookupService lookups;
|
||||
|
||||
public CacheDiagnosticsController(CacheManager cacheManager, BookService books,
|
||||
KeyShapeService shapes, LookupService lookups) {
|
||||
this.cacheManager = cacheManager;
|
||||
this.books = books;
|
||||
this.shapes = shapes;
|
||||
this.lookups = lookups;
|
||||
}
|
||||
|
||||
/** Calls a handful of cached methods so {@code /diag/caches} has something to show. */
|
||||
@GetMapping("/warm")
|
||||
public String warm() {
|
||||
books.findBook("978-0134685991");
|
||||
shapes.zeroArgs();
|
||||
shapes.oneArg("abc");
|
||||
shapes.twoArgs("abc", 7);
|
||||
lookups.searchCachingNulls("xyz");
|
||||
return "warmed: books, shapes, nulls";
|
||||
}
|
||||
|
||||
@GetMapping("/caches")
|
||||
public Map<String, Object> caches() {
|
||||
Map<String, Object> report = new LinkedHashMap<>();
|
||||
report.put("cacheManager", cacheManager.getClass().getName());
|
||||
Map<String, Object> caches = new LinkedHashMap<>();
|
||||
for (String name : cacheManager.getCacheNames()) {
|
||||
caches.put(name, describe(cacheManager.getCache(name)));
|
||||
}
|
||||
report.put("caches", caches);
|
||||
return report;
|
||||
}
|
||||
|
||||
private Map<String, Object> describe(Cache cache) {
|
||||
Map<String, Object> info = new LinkedHashMap<>();
|
||||
if (cache == null) {
|
||||
return info;
|
||||
}
|
||||
info.put("implementation", cache.getClass().getName());
|
||||
Object native_ = cache.getNativeCache();
|
||||
info.put("nativeStore", native_.getClass().getName());
|
||||
if (cache instanceof ConcurrentMapCache map) {
|
||||
Map<String, String> entries = new TreeMap<>();
|
||||
map.getNativeCache().forEach((k, v) -> entries.put(
|
||||
k + " [" + k.getClass().getSimpleName() + "]",
|
||||
v + " [" + v.getClass().getSimpleName() + "]"));
|
||||
info.put("entries", entries);
|
||||
}
|
||||
return info;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.ankurm.caching.eviction;
|
||||
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.CachePut;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* Eviction timing. {@code @CacheEvict} defaults to <em>after</em> a successful invocation, which
|
||||
* means a method that throws leaves the stale entry in place — and the next reader gets a value
|
||||
* the database no longer has.
|
||||
*
|
||||
* @see <a href="../../../../../../docs/05-eviction.md">docs/05-eviction.md</a>
|
||||
*/
|
||||
@Service
|
||||
public class PriceService {
|
||||
|
||||
private final AtomicInteger reads = new AtomicInteger();
|
||||
private int storedPrice = 100;
|
||||
|
||||
@Cacheable("prices")
|
||||
public int price(String sku) {
|
||||
reads.incrementAndGet();
|
||||
return storedPrice;
|
||||
}
|
||||
|
||||
/** Default timing: evict after the method returns normally. */
|
||||
@CacheEvict(cacheNames = "prices", key = "#sku")
|
||||
public void updatePrice(String sku, int newPrice, boolean fail) {
|
||||
storedPrice = newPrice;
|
||||
if (fail) {
|
||||
throw new IllegalStateException("audit log write failed after the price was updated");
|
||||
}
|
||||
}
|
||||
|
||||
/** Evict first, whatever happens next. Costs a cache miss; buys correctness on failure. */
|
||||
@CacheEvict(cacheNames = "prices", key = "#sku", beforeInvocation = true)
|
||||
public void updatePriceEvictFirst(String sku, int newPrice, boolean fail) {
|
||||
storedPrice = newPrice;
|
||||
if (fail) {
|
||||
throw new IllegalStateException("audit log write failed after the price was updated");
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes through instead of evicting: one fewer miss, but the value must be the real one. */
|
||||
@CachePut(cacheNames = "prices", key = "#sku")
|
||||
public int updatePriceWriteThrough(String sku, int newPrice) {
|
||||
storedPrice = newPrice;
|
||||
return newPrice;
|
||||
}
|
||||
|
||||
public int reads() { return reads.get(); }
|
||||
public void reset(int price) { reads.set(0); storedPrice = price; }
|
||||
public int storedPrice() { return storedPrice; }
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.ankurm.caching.jpa;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.OneToMany;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A deliberately ordinary entity with one lazy collection, used to show the boundary between
|
||||
* the Spring cache abstraction (which caches whatever object a method returned) and the
|
||||
* Hibernate second-level cache (which caches entity state Hibernate can rehydrate).
|
||||
*
|
||||
* @see <a href="../../../../../../docs/09-versus-hibernate-l2.md">docs/09-versus-hibernate-l2.md</a>
|
||||
*/
|
||||
@Entity
|
||||
public class Customer {
|
||||
|
||||
@Id
|
||||
private Long id;
|
||||
private String name;
|
||||
|
||||
@OneToMany(mappedBy = "customer", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
|
||||
private List<Order> orders = new ArrayList<>();
|
||||
|
||||
protected Customer() {
|
||||
}
|
||||
|
||||
public Customer(Long id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Long getId() { return id; }
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
public List<Order> getOrders() { return orders; }
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.ankurm.caching.jpa;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface CustomerRepository extends JpaRepository<Customer, Long> {
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.ankurm.caching.jpa;
|
||||
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.CachePut;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* Caching and transactions. The caching interceptor runs inside the transaction interceptor,
|
||||
* so a cache write happens at method exit — before the commit, and regardless of whether the
|
||||
* commit succeeds.
|
||||
*
|
||||
* @see <a href="../../../../../../docs/10-transactions.md">docs/10-transactions.md</a>
|
||||
*/
|
||||
@Service
|
||||
public class CustomerService {
|
||||
|
||||
private final CustomerRepository repository;
|
||||
private final AtomicInteger loads = new AtomicInteger();
|
||||
|
||||
public CustomerService(CustomerRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
@Cacheable("customers")
|
||||
@Transactional(readOnly = true)
|
||||
public String nameOf(Long id) {
|
||||
loads.incrementAndGet();
|
||||
return repository.findById(id).map(Customer::getName).orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* An ordinary, correct-looking write-through update. It succeeds; the caller is what fails.
|
||||
* Joins the caller's transaction, so the row is rolled back with it.
|
||||
*/
|
||||
@CachePut(cacheNames = "customers", key = "#id")
|
||||
@Transactional
|
||||
public String rename(Long id, String newName) {
|
||||
Customer customer = repository.findById(id).orElseThrow();
|
||||
customer.setName(newName);
|
||||
repository.saveAndFlush(customer);
|
||||
return newName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Evicts before the body runs. Under a transaction-aware cache manager the evict is still
|
||||
* deferred to commit, which is measured in {@code docs/output/19-transaction-aware.txt}.
|
||||
*/
|
||||
@CacheEvict(cacheNames = "customers", key = "#id", beforeInvocation = true)
|
||||
@Transactional
|
||||
public void renameEvictingFirst(Long id, String newName) {
|
||||
Customer customer = repository.findById(id).orElseThrow();
|
||||
customer.setName(newName);
|
||||
repository.saveAndFlush(customer);
|
||||
}
|
||||
|
||||
/** The same update expressed as an eviction rather than a write-through. */
|
||||
@CacheEvict(cacheNames = "customers", key = "#id")
|
||||
@Transactional
|
||||
public void renameEvicting(Long id, String newName) {
|
||||
Customer customer = repository.findById(id).orElseThrow();
|
||||
customer.setName(newName);
|
||||
repository.saveAndFlush(customer);
|
||||
}
|
||||
|
||||
/** Returns a managed entity that becomes detached the moment the transaction ends. */
|
||||
@Cacheable("entities")
|
||||
@Transactional(readOnly = true)
|
||||
public Customer loadEntity(Long id) {
|
||||
loads.incrementAndGet();
|
||||
return repository.findById(id).orElseThrow();
|
||||
}
|
||||
|
||||
public int loads() { return loads.get(); }
|
||||
public void reset() { loads.set(0); }
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.ankurm.caching.jpa;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
/**
|
||||
* The outer transaction. {@code rename} is a perfectly ordinary cached write that succeeds; the
|
||||
* work after it fails. The database change is rolled back and the cache write is not, because
|
||||
* the caching interceptor sits inside the transaction interceptor and fires at method exit.
|
||||
*
|
||||
* @see <a href="../../../../../../docs/10-transactions.md">docs/10-transactions.md</a>
|
||||
*/
|
||||
@Service
|
||||
public class CustomerWorkflow {
|
||||
|
||||
private final CustomerService customers;
|
||||
|
||||
public CustomerWorkflow(CustomerService customers) {
|
||||
this.customers = customers;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void renameAndThenFail(Long id, String newName) {
|
||||
customers.rename(id, newName);
|
||||
throw new IllegalStateException("the step after the rename failed");
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void evictAndThenFail(Long id, String newName) {
|
||||
customers.renameEvicting(id, newName);
|
||||
throw new IllegalStateException("the step after the rename failed");
|
||||
}
|
||||
|
||||
/**
|
||||
* Evicts before the inner method body, then reads the cache again while still inside the
|
||||
* same transaction. On a plain cache manager the entry is already gone; on a
|
||||
* transaction-aware one it is not, because the evict was deferred to commit.
|
||||
*/
|
||||
@Transactional
|
||||
public String evictFirstThenReadInSameTransaction(Long id, String newName) {
|
||||
customers.renameEvictingFirst(id, newName);
|
||||
return customers.nameOf(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.ankurm.caching.jpa;
|
||||
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
/**
|
||||
* Two customers and two orders, so the JPA demonstrations have something to load.
|
||||
*/
|
||||
@Configuration
|
||||
public class DataSeeder {
|
||||
|
||||
@Bean
|
||||
ApplicationRunner seed(CustomerRepository repository) {
|
||||
return args -> seedData(repository);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
void seedData(CustomerRepository repository) {
|
||||
if (repository.count() > 0) {
|
||||
return;
|
||||
}
|
||||
Customer alice = new Customer(1L, "Alice");
|
||||
alice.getOrders().add(new Order(10L, "keyboard", alice));
|
||||
alice.getOrders().add(new Order(11L, "monitor", alice));
|
||||
repository.save(alice);
|
||||
repository.save(new Customer(2L, "Bob"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.ankurm.caching.jpa;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "orders")
|
||||
public class Order {
|
||||
|
||||
@Id
|
||||
private Long id;
|
||||
private String item;
|
||||
|
||||
@ManyToOne
|
||||
private Customer customer;
|
||||
|
||||
protected Order() {
|
||||
}
|
||||
|
||||
public Order(Long id, String item, Customer customer) {
|
||||
this.id = id;
|
||||
this.item = item;
|
||||
this.customer = customer;
|
||||
}
|
||||
|
||||
public Long getId() { return id; }
|
||||
public String getItem() { return item; }
|
||||
public Customer getCustomer() { return customer; }
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.ankurm.caching.keys;
|
||||
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* The default key generator uses the arguments and <em>nothing else</em> — not the method name,
|
||||
* not the declaring class. Two methods that share a cache name and take the same argument types
|
||||
* therefore share a key space, and the second one silently serves the first one's values.
|
||||
*
|
||||
* <p>{@code countLetters} and {@code countDigits} below are deliberately obvious. The real bug
|
||||
* looks like {@code findByIsbn} and {@code findByTitle} sitting next to each other in a service.
|
||||
*
|
||||
* @see <a href="../../../../../../docs/04-keys.md">docs/04-keys.md</a>
|
||||
*/
|
||||
@Service
|
||||
public class CollidingService {
|
||||
|
||||
private final AtomicInteger letterCalls = new AtomicInteger();
|
||||
private final AtomicInteger digitCalls = new AtomicInteger();
|
||||
private final AtomicInteger noArgCalls = new AtomicInteger();
|
||||
|
||||
@Cacheable("shared")
|
||||
public String countLetters(String input) {
|
||||
letterCalls.incrementAndGet();
|
||||
return "letters=" + input.chars().filter(Character::isLetter).count();
|
||||
}
|
||||
|
||||
@Cacheable("shared")
|
||||
public String countDigits(String input) {
|
||||
digitCalls.incrementAndGet();
|
||||
return "digits=" + input.chars().filter(Character::isDigit).count();
|
||||
}
|
||||
|
||||
/** No arguments means the key is {@code SimpleKey.EMPTY} — a single shared constant. */
|
||||
@Cacheable("noargs")
|
||||
public String currentBanner() {
|
||||
noArgCalls.incrementAndGet();
|
||||
return "banner-from-currentBanner";
|
||||
}
|
||||
|
||||
/** Also no arguments, also {@code SimpleKey.EMPTY}, also in cache {@code noargs}. */
|
||||
@Cacheable("noargs")
|
||||
public String currentFooter() {
|
||||
noArgCalls.incrementAndGet();
|
||||
return "footer-from-currentFooter";
|
||||
}
|
||||
|
||||
/** The fix: make the key say which method it belongs to. */
|
||||
@Cacheable(cacheNames = "scoped", key = "'letters:' + #input")
|
||||
public String countLettersScoped(String input) {
|
||||
letterCalls.incrementAndGet();
|
||||
return "letters=" + input.chars().filter(Character::isLetter).count();
|
||||
}
|
||||
|
||||
@Cacheable(cacheNames = "scoped", key = "'digits:' + #input")
|
||||
public String countDigitsScoped(String input) {
|
||||
digitCalls.incrementAndGet();
|
||||
return "digits=" + input.chars().filter(Character::isDigit).count();
|
||||
}
|
||||
|
||||
public int letterCalls() { return letterCalls.get(); }
|
||||
public int digitCalls() { return digitCalls.get(); }
|
||||
public int noArgCalls() { return noArgCalls.get(); }
|
||||
public void reset() { letterCalls.set(0); digitCalls.set(0); noArgCalls.set(0); }
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.ankurm.caching.keys;
|
||||
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Prints the key object the abstraction actually built, for zero, one and several arguments,
|
||||
* and shows what a mutable argument does to a key.
|
||||
*
|
||||
* @see <a href="../../../../../../docs/04-keys.md">docs/04-keys.md</a>
|
||||
*/
|
||||
@Service
|
||||
public class KeyShapeService {
|
||||
|
||||
@Cacheable("shapes")
|
||||
public String zeroArgs() {
|
||||
return "zero";
|
||||
}
|
||||
|
||||
@Cacheable("shapes")
|
||||
public String oneArg(String a) {
|
||||
return "one:" + a;
|
||||
}
|
||||
|
||||
@Cacheable("shapes")
|
||||
public String twoArgs(String a, int b) {
|
||||
return "two:" + a + ":" + b;
|
||||
}
|
||||
|
||||
/** A mutable argument is a key you can lose. */
|
||||
@Cacheable("mutable")
|
||||
public String byList(List<String> tags) {
|
||||
return "tags=" + tags;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.ankurm.caching.selfinvocation;
|
||||
|
||||
import com.ankurm.caching.basics.Book;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Fix 3, and the one worth reaching for: the loop lives in a different bean, so the call to
|
||||
* {@code lookup} is an ordinary external call and goes through the proxy like any other.
|
||||
*
|
||||
* @see <a href="../../../../../../docs/03-self-invocation.md">docs/03-self-invocation.md</a>
|
||||
*/
|
||||
@Service
|
||||
public class CatalogReader {
|
||||
|
||||
private final CatalogService catalog;
|
||||
|
||||
public CatalogReader(CatalogService catalog) {
|
||||
this.catalog = catalog;
|
||||
}
|
||||
|
||||
public List<Book> byCollaborator(List<String> isbns) {
|
||||
return isbns.stream().map(catalog::lookup).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.ankurm.caching.selfinvocation;
|
||||
|
||||
import com.ankurm.caching.basics.Book;
|
||||
import com.ankurm.caching.basics.BookRepositoryStub;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import org.springframework.aop.framework.AopContext;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Four ways to call a {@code @Cacheable} method from inside the same bean. One of them caches
|
||||
* nothing, and it is the one everybody writes first.
|
||||
*
|
||||
* <p>The mechanism: {@code @EnableCaching} does not rewrite {@code CatalogService}. It puts a
|
||||
* proxy in front of it, and the caching interceptor lives in the proxy. {@code this.lookup(..)}
|
||||
* is a plain virtual call on the target object; it never crosses the proxy, so no interceptor
|
||||
* runs.
|
||||
*
|
||||
* @see <a href="../../../../../../docs/03-self-invocation.md">docs/03-self-invocation.md</a>
|
||||
*/
|
||||
@Service
|
||||
public class CatalogService {
|
||||
|
||||
private final BookRepositoryStub repository;
|
||||
/** A provider, not the bean itself: injecting the proxy into its own constructor is a cycle. */
|
||||
private final ObjectProvider<CatalogService> self;
|
||||
|
||||
public CatalogService(BookRepositoryStub repository, ObjectProvider<CatalogService> self) {
|
||||
this.repository = repository;
|
||||
this.self = self;
|
||||
}
|
||||
|
||||
@Cacheable("catalog")
|
||||
public Book lookup(String isbn) {
|
||||
return repository.load(isbn);
|
||||
}
|
||||
|
||||
/** Broken: {@code this.lookup} bypasses the proxy, so every ISBN hits the repository. */
|
||||
public List<Book> byInternalCall(List<String> isbns) {
|
||||
return isbns.stream().map(this::lookup).toList();
|
||||
}
|
||||
|
||||
/** Fix 1: go back out through the proxy that the container is holding. */
|
||||
public List<Book> bySelfInjection(List<String> isbns) {
|
||||
CatalogService proxy = self.getObject();
|
||||
return isbns.stream().map(proxy::lookup).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fix 2: {@code @EnableCaching(exposeProxy = true)} binds the current proxy to a ThreadLocal.
|
||||
* Works, but it couples the code to Spring AOP and only inside an intercepted call.
|
||||
*/
|
||||
public List<Book> byExposedProxy(List<String> isbns) {
|
||||
CatalogService proxy = (CatalogService) AopContext.currentProxy();
|
||||
return isbns.stream().map(proxy::lookup).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Silently uncached for a second, independent reason: in proxy mode the annotation is only
|
||||
* honoured on public methods. No warning is logged.
|
||||
*/
|
||||
@Cacheable("catalog")
|
||||
protected Book protectedLookup(String isbn) {
|
||||
return repository.load(isbn);
|
||||
}
|
||||
|
||||
public Book callProtected(String isbn) {
|
||||
return protectedLookup(isbn);
|
||||
}
|
||||
|
||||
/** The proxy is not in place yet during {@code @PostConstruct}. Documented, still surprising. */
|
||||
@PostConstruct
|
||||
void warmUpThatDoesNotWarmAnything() {
|
||||
lookup("978-0134685991");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.ankurm.caching.sync;
|
||||
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* Since Spring Framework 6.1 the cache annotations understand {@code CompletableFuture} and
|
||||
* reactive return types. The cache has to support future-based retrieval: {@code
|
||||
* ConcurrentMapCacheManager} adapts automatically, {@code CaffeineCacheManager} needs
|
||||
* {@code setAsyncCacheMode(true)}.
|
||||
*
|
||||
* @see <a href="../../../../../../docs/07-sync-and-async.md">docs/07-sync-and-async.md</a>
|
||||
*/
|
||||
@Service
|
||||
public class AsyncReportService {
|
||||
|
||||
private final AtomicInteger calls = new AtomicInteger();
|
||||
|
||||
@Cacheable("asyncReports")
|
||||
public CompletableFuture<String> buildAsync(String name) {
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
calls.incrementAndGet();
|
||||
return "async-report:" + name;
|
||||
});
|
||||
}
|
||||
|
||||
public int calls() { return calls.get(); }
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.ankurm.caching.sync;
|
||||
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* Cache stampede. Without {@code sync = true}, N threads that miss at the same instant all run
|
||||
* the method; with it, one runs and the rest block on the same computation.
|
||||
*
|
||||
* @see <a href="../../../../../../docs/07-sync-and-async.md">docs/07-sync-and-async.md</a>
|
||||
*/
|
||||
@Service
|
||||
public class ReportService {
|
||||
|
||||
private final AtomicInteger unsyncedCalls = new AtomicInteger();
|
||||
private final AtomicInteger syncedCalls = new AtomicInteger();
|
||||
|
||||
@Cacheable("reports")
|
||||
public String buildReport(String name) {
|
||||
unsyncedCalls.incrementAndGet();
|
||||
sleep(300);
|
||||
return "report:" + name;
|
||||
}
|
||||
|
||||
@Cacheable(cacheNames = "syncedReports", sync = true)
|
||||
public String buildReportSynced(String name) {
|
||||
syncedCalls.incrementAndGet();
|
||||
sleep(300);
|
||||
return "report:" + name;
|
||||
}
|
||||
|
||||
public int unsyncedCalls() { return unsyncedCalls.get(); }
|
||||
public int syncedCalls() { return syncedCalls.get(); }
|
||||
|
||||
private static void sleep(long ms) {
|
||||
try {
|
||||
Thread.sleep(ms);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
spring:
|
||||
application:
|
||||
name: caching
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: create-drop
|
||||
open-in-view: false
|
||||
properties:
|
||||
hibernate:
|
||||
cache:
|
||||
# Explicit: this module is about the *application* cache, not Hibernate's L2.
|
||||
# See docs/09-versus-hibernate-l2.md for what the difference actually buys you.
|
||||
use_second_level_cache: false
|
||||
sql:
|
||||
init:
|
||||
mode: never
|
||||
|
||||
management:
|
||||
endpoints:
|
||||
web:
|
||||
exposure:
|
||||
include: caches,metrics,health
|
||||
|
||||
logging:
|
||||
level:
|
||||
org.springframework.cache: INFO
|
||||
Reference in New Issue
Block a user