present (sb for a job etc)
Spring Cache is a framework that implements an annotation-based caching functionality , just simply add an annotation , you can achieve caching functionality , greatly simplifying our business in the operation of the cache code .
Spring Cache just provides a layer of abstraction, the bottom can switch between different cache implementations. Specifically through the CacheManager interface to unify the different caching technologies . CacheManager is Spring provides a variety of caching technology abstraction interface.
Different CacheManagers need to be implemented for different caching technologies:
CacheManager |
descriptive |
EhCacheCacheManager |
Using EhCache as a caching technique |
GuavaCacheManager |
Using Google's GuavaCache as a caching technique |
RedisCacheManager |
utilizationRedisAs a caching technique |
explanatory note
existSpringCacheThere are a number of annotations provided for caching operations, the common ones being the following:
annotate |
clarification |
@EnableCaching |
Enable caching annotations , add the |
@Cacheable |
Before the method is executed spring first check whether there is data in the cache, if there is data, then directly return the cached data; if there is no data, call the method and put the method return value into the cache |
@CachePut |
Putting the return value of a method into the cache |
@CacheEvict |
Remove one or more pieces of data from the cache |
In a spring boot project, all you need to do to use caching is to import the relevant caching dependency packages in the project and turn on caching support using @EnableCaching on the startup class.
For example, to use Redis as a caching technology, simply import the Spring data RedismavenCoordinates are sufficient.
Use SpringCach main attention to the design of the key, because the cache data, you may want to cache a number of copies of these data can not be mixed up, it is necessary to distinguish according to the key, and the key is often dynamic, for example, I dynamically use the current user's id as the key, how to get the id, it provides us with a kind ofSPEL expressionlanguage, in this way it is possible to dynamically obtain the user's di
For example, the key to get the id of an object is written as follows: both can be used, and it is recommended to use them because the id is unique.
# : #user refers to the name of the method's formal parameter, id refers to the user's id attribute, i.e., the user's id attribute is used as the key.
#: #user refers to the name of the method's formal parameter, name refers to the name attribute of the user, i.e., the name attribute of the user is used as the key.
# : #result represents the return value of the method, and this expression represents the id attribute of the returned object as the key;
# : #result represents the return value of the method, and this expression represents the name attribute of the returned object as the key;
To use redis for caching, you need to do the following steps:
Steps to use Spring Cache in a Spring Boot project (using redis caching technology)
1. Importing maven coordinates.spring-boot-starter-cache , spring-boot-starter-data-redis
2. Configuration Setting the cache validity period
3. Write Redis configuration class RedisConfig, define RedisTemplate.
4. Add the @EnableCaching annotation to the startup class to enable the caching annotation.
5. Add @Cacheable . @CacheEvict , @CachePut , etc. , for caching operations.
1). Import 2 maven coordinates spring-boot-starter-cache , spring-boot-starter-data-redis
-
<dependency>
-
<groupId></groupId>
-
<artifactId>spring-boot-starter-cache</artifactId>
-
</dependency>
-
-
<dependency>
-
<groupId></groupId>
-
<artifactId>spring-boot-starter-data-redis</artifactId>
-
</dependency>
2). Configuration Add redis related configuration , set cache validity period
-
spring:
-
redis:
-
host: 172.0.0.1
-
port: 6379
-
password: 123456 # Own password
-
database: 0
-
cache:
-
redis:
-
time-to-live: 1800000 # Setting the cache expiration time30Minutes, optional
3). Write the Redis configuration class RedisConfig, define the RedisTemplate
Framework default declaration of the RedisTemplate with the key and value serialization is the default JdkSerializationRedisSerializer, if the key is serialized in this way, we end up in the test through the redis graphical interface query is not very convenient, so use our customized RedisTemplate, the key is serialized using the StringRedisSerializer, that is, string form
-
import .CachingConfigurerSupport;
-
import .Bean;
-
import .Configuration;
-
import .RedisConnectionFactory;
-
import .RedisTemplate;
-
import .StringRedisSerializer;
-
-
@Configuration
-
public class RedisConfig extends CachingConfigurerSupport {
-
@Bean
-
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
-
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
-
// The default Key serializer is: JdkSerializationRedisSerializer
-
(new StringRedisSerializer());
-
(connectionFactory);
-
return redisTemplate;
-
}
-
}
4). Add the @EnableCaching annotation to the startup class to enable the caching annotation.
5). Add @Cacheable . @CacheEvict , @CachePut , etc. , to perform caching operations.
1. @Cacheble a Note Description.
Role: Before the method is executed, spring first check whether there is data in the cache, if there is data, then directly return the cached data; if there is no data, call the method and put the method return value to the cache
value: the name of the cache, there can be more than one key under each cache name
key: cached key ----------> support Spring's Expression Language SPEL syntax
condition : Indicates what conditions are met before caching.
unless : does not cache if the condition is met; the reverse of condition above.
-
/**
-
* :: Cacheable: before the method is executed spring first check whether there is data in the cache, if there is data, then directly return the cached data; if there is no data, call the method and put the method return value into cache
-
* :: value: the name of the cache, there can be more than one key under each cache name
-
* :: key: cached key
-
* condition: conditions, meet the conditions before caching the data , can not use the result inside is no result object.
-
* :: unless: no caching if conditions are met
-
*/
-
@Cacheable(value = "userCache",key = "#id", unless = "#result == null")
-
@GetMapping("/{id}")
-
public User getById(@PathVariable Long id){
-
User user = (id);
-
return user;
-
}
Annotate the list method with @Cacheable
When querying in the list method, there are two query conditions, if you pass the id, according to the id query; if you pass the name, according to the name query, then we cache the key in the design, we need to include both id and name.
-
@Cacheable(value = "userCache",key = "# + '_' + #")
-
@GetMapping("/list")
-
public List<User> list(User user){
-
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
-
(() != null,User::getId,());
-
(() != null,User::getName,());
-
List<User> list = (queryWrapper);
-
return list;
-
}
2. @CacheEvict annotation:
Function: Clears the specified cache
value: the name of the cache, there can be more than one key under each cache name
key: cached key ----------> supports Spring's Expression Language SPEL syntax , can dynamically calculate the value of the key
1). Add the @CacheEvict annotation to the delete method When we delete data from the user table in the database, we need to delete the corresponding data in the cache, and then we can use the @CacheEvict annotation, which is used as follows.
-
* CacheEvict: Clears the specified cache.
-
* value: the name of the cache, there can be more than one under each cache namekey
-
* keycachedkey
-
*/
-
//@CacheEvict(value = "userCache",key = "#p0") //#p0 Represents the first parameter
-
//@CacheEvict(value = "userCache",key = "#[0]") //#[0] represents the first parameter
-
@CacheEvict(value = "userCache",key = "#id") //#id Represents a parameter with variable name id Recommended Use
-
@DeleteMapping("/{id}")
-
public void delete(@PathVariable Long id){
-
(id);
-
}
2). Add the annotation @CacheEvict to the update method After updating the data, the data in the database has changed, and we need to remove the corresponding data from the cache to avoid inconsistencies between the database data and the cached data.
-
//@CacheEvict(value = "userCache",key = "#") //The id attribute of the first parameter
-
-
//@CacheEvict(value = "userCache",key = "#[0].id") //The id attribute of the first parameter
-
//@CacheEvict(value = "userCache",key = "#") //The id attribute of the return value
-
@CacheEvict(value = "userCache",key = "#") //The id attribute of the parameter named user parameter
-
@PutMapping
-
public User update(User user){
-
(user);
-
return user;
-
}
3) Add new package Clear cache for deleted packages allEntries = true
-
/**
-
* :: Deletion of packages
-
* @param ids
-
* @return
-
*/
-
@DeleteMapping
-
@CacheEvict(value = "setmealCache",allEntries = true) //Clear all cached data under the name setmealCache.
-
public R<String> delete(@RequestParam List<Long> ids){
-
("ids:{}",ids);
-
(ids);
-
return ("Package data deleted successfully.");
-
}
-
-
-
**
-
* :: New packages added
-
* @param setmealDto
-
* @return
-
*/
-
@PostMapping
-
@CacheEvict(value = "setmealCache",allEntries = true) //Clear all cached data under the name setmealCache.
-
public R<String> save(@RequestBody SetmealDto setmealDto){
-
("Package information: {}",setmealDto);
-
-
(setmealDto);
-
-
return ("New package added successfully");
-
}
3 . @CachePut annotation description:
What it does: puts the return value of the method into the cache.
value: the name of the cache, each cache name can have many keys under it
key: cached key ----------> support Spring's Expression Language SPEL syntax
1). Annotate the save method with @CachePut
The save method is used to save the user's information. If we want to cache a copy of the user's information while it is being saved to the database, we can add the @CachePut annotation to the save method.
-
/**
-
* CachePut: puts method return values into the cache The underlying cache used now is Map
-
* value: the name of the cache, there can be more than one under each cache namekey
-
* keycachedkey
-
*/
-
@CachePut(value = "userCache", key = "#")
-
@PostMapping
-
public User save(User user){
-
(user);
-
return user;
-
}