java / intermediate
Snippet
Performance Optimization with @Cacheable
Spring Cache abstraction allows you to transparently cache expensive operations. Subsequent calls with the same ID will return the cached value instead of executing the method body.
snippet.java
1
2
3
4
5
6
7
8
@Servicepublic class ProductService {@Cacheable(value = "products", key = "#id")public Product getProductById(Long id) {// Simulated slow database callreturn repository.findById(id).orElseThrow();}}
spring
Breakdown
1
@Cacheable(value = "products", key = "#id")
Specifies the cache name and the dynamic key used for lookup.