Basic concepts and principles
Processing logic
Spring Cache is a complete caching solution provided by Spring。
Although it does not provide cache implementation itself, it provides a complete set of interfaces and code specifications, configurations, annotations, etc., so that it can integrate various cache solutions.
Processing logic:
Every time a method is called and this method has a cache function, the Spring framework will check whether the method of the specified parameter has been called.If it has been called before, the result of the previous call is retrieved from the cache;ifIf you have not called it, then call this method again, cache the result, and then return the result. The next time you call this method, you can directly get the result from the cache.。
Implementation steps
SpringCache implementation steps:
-
Enable cache: triggers Spring's cache proxy configuration via the @EnableCaching annotation
。 -
AOP Intercept
: Spring generates a proxy object for the tag annotation method, inserting cache operations before and after the method call. -
Cache processing
: According to the annotation configuration, call CacheManager to obtain the Cache instance and perform read, write or delete operations.
Core Principle
The core principles of Spring Cache are based onAOP (System-Oriented Programming) and Cache Abstraction
, simplifies the integration of cache logic through annotations.
ThatThe core is the cache abstraction layer and the dynamic proxy mechanism
, combined with Spring Boot's automatic configuration, it can quickly integrate multiple cache solutions, significantly improving system performance
Spring Cache decouples concrete cache technology through abstraction layer:
-
Adapter mode
: Adapt different cache implementations (such as Redis, Ehcache) through CacheManager and Cache interfaces. -
Automatic configuration
: Spring Boot's spring-boot-autoconfigure moduleAutomatically detect and configure cache implementation(For example, the Redis cache is automatically enabled after the introduction of spring-boot-starter-data-redis).
Core components and abstractions
Cache interface: define cache operations (such as get, put, and evict)
, the specific implementation is provided by third-party caching technologies (such as Redis, Caffeine).
CacheManager interface: manages multiple Cache instances, responsible for creating, configuring, and obtaining cache objects
。
For example:
ConcurrentMapCacheManager (default memory cache) RedisCacheManager (Redis implementation) EhCacheCacheManager (Ehcache implementation)
Core notes
Spring provides five annotations to declare cache rules.
@Cacheable: Check the cache before the method is executed, and returns directly if it hits, otherwise the method is executed and the result is cached.
@CachePut: The method will not be searched in the cache before the method is called. Regardless of whether the cache exists or not, the method will be executed and the cache will be updated.
@CacheEvict: Delete the specified cache and clear one or more records in the cache
@Caching: Combining multiple cache operations.
@CacheConfig: Configuration that shares the same cache at the class level
annotation | effect | Common parameters |
---|---|---|
@Cacheable | Method result cache (check the cache first, miss the execution method), which is generally used in query methods | value, key, condition |
@CachePut | Forced update of cache (always executed method), generally used in new methods | value, key, unless |
@CacheEvict | Clear cache, generally used in update or delete methods | value, key, allEntries |
@Caching | Combining multiple cache operations to achieve the use of multiple annotations on the same method at the same time | cacheable, put, evict |
@CacheConfig | Class-level shared cache configuration | cacheNames, keyGenerator |
SpEL expressions
Scene | Expression example |
---|---|
Anti-cache penetration | unless = “#result == null” |
Multi-field composite key | key = “# + ‘:’ + #” |
Timestamp dynamic key | key = “T(System).currentTimeMillis()” |
Permission filtering | condition = “#authLevel > 3” |
Set non-empty judgment | condition = “!#()” |
accomplish
pom dependency
<dependency> <groupId></groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
Select the cache to use
# Use redis for caching=redis
Spring Cache supports many cache middleware as cache in the framework, with a total of 9 options:
- caffeine: Caffeine is a high-performance cache library based on Google Guava.
- couchbase: CouchBase is a non-relational JSON document database.
- generic: a generic cache mechanism implemented by a combination of generic mechanisms and static.
- hazelcast: A highly scalable data distribution and clustering platform that can be used to implement distributed data storage and data caching.
- infinispan: a distributed cluster cache system.
- jcache: JCache as cache. It is the cache specification mentioned in the JSR107 specification.
- none: No cache.
- redis: Use Redis as cache
- simple: Use memory as cache
Basic concepts
existAdd @EnableCaching annotation on the startup class
Specify a method to enable the cache function. Just add the @Cacheable cache annotation to the method。
In the @Cacheable annotation, four parameters can be added: value, key, condition, unless
- value: Specify the cache name (required)
- key: Custom cache key (SpEL expression)
- condition: Pre-execution condition judgment (SpEL)
- unless: After execution result filtering (SpEL)
parameter | type | effect | Example |
---|---|---|---|
value | String[] | Specify the cache name (required) | value = "users" or value = {"cache1", "cache2"} |
key | String | Custom cache keys (SpEL expressions) | key = "#userId" or key = "T().randomUUID().toString()" |
condition | String | Pre-execution condition judgment (SpEL) | condition = "#userId > 1000" or condition = "#('admin')" |
unless | String | After execution result filtering (SpEL) | unless = "#result == null" or unless = "# < 18" |
Example 1
Before calling the following interface for the first time, there is no hot cache in the cache, and there is no result cache for this test method.
After calling the test method, a cache of hot will be created in the cache, which is cached with a key (the default value SimpleKey[]), and there is a value.
- The value corresponding to the key in the cache uses the JDK serialized data by default.
- The expiration time of value is -1, indicating that it never expires.
key:hot:SimpleKey[]
value:222
@RequestMapping("/test2") @Cacheable({"hot"}) public int test() { return 222; }
The second time you call the test() method, the cache will be read directly without executing the methods in the test
@RequestMapping("/test2") @Cacheable({"hot"}) public int test2() { return 456; }
If the class name is changed to test2, the value obtained by the cache is still the value 222 cached when the test method is tested, because the key values of both methods are SimpleKey[]
Example 2
// Enable cache (configuration class)@EnableCaching @Configuration public class CacheConfig { @Bean public CacheManager cacheManager() { return new ConcurrentMapCacheManager("users"); // Memory cache } } // Use of the business layer@Service public class UserService { // cache read (value=cache name, key=cache key) @Cacheable(value = "users", key = "#userId") public User getUserById(Long userId) { // Actual database query return (userId); } // Cache update @CachePut(value = "users", key = "#") public User updateUser(User user) { return (user); } // Cache clearance @CacheEvict(value = "users", key = "#userId") public void deleteUser(Long userId) { (userId); } }
Custom configuration class
Custom cache past time, etc.
# Use Redis as cache component=redis # The cache expiration time is 3600s-to-live=3600000 # The name prefix of the cached key-prefix=passjava_ # Whether to use cache prefix-key-prefix=true # Whether to cache control to prevent cache penetration-null-values=true
Custom key
Add the value of key # into the @Cacheable annotation. This is a unique expression called a SpEL expression, hereName that represents the method name as cache key
@Cacheable(value = {"hot"}, key = "#")
If configured as described above, the cached key name is this method name
Custom conditions
You can customize the conditions to decide whether to turn off the cache function. Here we need to use the other two properties of @Cacheable: condition and unless. The format of them is still using SpEL expressions.
This is the article about local cache in the spring framework: basic use of spring cache. For more related content on using spring cache, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!