Spring Cache is a framework that implements annotation-based caching function. You only need to simply add an annotation to implement caching. Function.
Spring Cache provides a layer of abstraction, and the bottom layer can switch different cache implementations.
Specifically, different caching technologies are unified through the CacheManager interface.
CacheManager is an abstract interface for various caching technologies provided by Spring. This is the default caching technology and is cached in Map. This also means that when the service hangs up, the cached data will be gone.
Different CacheManagers need to be implemented for different caching technologies
CacheManager | Description |
---|---|
EhCacheCacheManager | Use EhCache as caching technology |
GuavaCacheManager | Use Google's GuavaCache as caching technology |
RedisCacheManager | Use Redis as caching technology |
In the Spring Boot project, To use caching technology, you only need to import the dependency package of the relevant caching technology into the project, and use @EnableCaching
on the startup class to enable caching support. For example, to use Redis as the caching technology, you only need to import the maven coordinates of Spring data Redis. Commonly used annotations are as follows:
Annotation | Explanation |
---|---|
@ EnableCaching | Enable cache annotation function |
@Cacheable | Before the method is executed, spring first checks whether there is data in the cache. If there is data, it directly Return cached data; if there is no data, call the method and put the method return value in the cache |
@CachePut | Put the method return value in the cache |
@CacheEvict | Delete one or more pieces of data from the cache |
The main function of this annotation is to enable the cache annotation function and make other Spring Cache annotations effective. The method of use is also very simple, just add it directly above the startup class of the project.
@Slf4j @SpringBootApplication @EnableCaching public class CacheDemoApplication { public static void main(String[] args) { SpringApplication.run(CacheDemoApplication.class, args); log.info("项目启动成功..."); } }
@Cacheable
annotation is mainly to check whether there is data in the cache before executing the method. If there is data, the cached data is returned directly; if there is no data, the method is called and the method return value is placed in the cache.
Parameter transfer in annotations mainly uses **SpEL (Spring Expression Language)** to obtain and transfer data, which is somewhat similar to EL expressions in JSP. Commonly used methods are as follows:
"#p0": Get the first parameter in the parameter list. The "#p" is a fixed writing method, 0 is the subscript, representing the first one;
"#root.args[0]": Get the first parameter in the method . Among them, 0 is the subscript, which represents the first one.
"#user.id": Get the id attribute of parameter user. Note that the user here must be consistent with the parameter name in the parameter list
"#result.id": Get the id attribute in the return value.
From Spring Cache source code: Spring Expression Language (SpEL) expression used for making the method
There are several commonly used in the @Cacheable
annotation The attributes can be set on demand:
value: The name of the cache. There can be multiple keys under each cache name
key: Cache key.
condition: condition judgment, cache the data when the condition is met. It is worth noting that this parameter is invalid in Redis
The parameter " unless" can be used in Redis as a conditional statement to avoid caching data if a certain condition is met.
/** * @description 通过id获取用户信息 * @author xBaozi * @date 14:23 2022/7/3 **/ @Cacheable(value = "userCache", key = "#id", unless = "#result == null") @GetMapping("/{id}") public User getById(@PathVariable Long id) { User user = userService.getById(id); return user; }
@CachPut
The annotation is mainly to put the return value of the method into the cache. SpEL is also used to obtain data here. Commonly used attributes are as follows:
value: The name of the cache. There can be multiple keys under each cache name
key: cached key.
condition: condition judgment, cache the data when the condition is met. It is worth noting that this parameter is invalid in Redis
The parameter " unless" can be used in Redis as a conditional statement to avoid caching data if a certain condition is met.
/** * @description 新增用户信息并返回保存的信息 * @author xBaozi * @date 14:38 2022/7/3 **/ @CachePut(value = "userCache", key = "#user.id") @PostMapping public User save(User user) { userService.save(user); return user; }
@CacheeEvict
Mainly deletes one or more pieces of data from the cache. SpEL is also used to obtain data. Commonly used attributes are as follows:
value: the name of the cache, below each cache name There can be multiple keys
key: cached key.
condition: condition judgment, cache the data when the condition is met. It is worth noting that this parameter is invalid in Redis
The parameter " unless" can be used in Redis as a conditional statement to avoid caching data if a certain condition is met.
/** * @description 更新用户信息 * @author xBaozi * @date 14:41 2022/7/3 **/ @CacheEvict(value = "userCache", key = "#result.id") @PutMapping public User update(User user) { userService.updateById(user); return user; }
because Spring's default caching technology cannot persist cache data. Even if the service hangs up, the cache will also hang up, so you need to use Redis for operation (in fact, it is also because you have learned Redis)
The previous SpringBoot integrated Redis cache verification code It records some basic operations of Redis.
Import maven coordinates: spring-boot-starter-data-redis, spring-boot-starter-cache
<!--Spring Data Redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!--Spring Cache--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
spring:
redis:
host: localhost
port: 6379
password: 123456
database: 0
cache:
redis:
Time-to-live: 1800000 # Set the cache validity period
Add it to the startup classcom/itheima/CacheDemoApplication.java
@EnableCaching annotation, enable cache annotation function
@Slf4j @SpringBootApplication @ServletComponentScan @EnableCaching public class ReggieApplication { public static void main(String[] args) { SpringApplication.run(ReggieApplication.class, args); log.info("springBoot项目启动成功……"); } }
, you need to be reminded that when using cache, the return value must implement the Serializable serialization interface, otherwise it will be thrown mistake.
This is because in the NoSql database, there is no data structure corresponding to our Java basic type, so when storing in the NoSql database, we must serialize the object, and at the same time during network transmission we It should be noted that the serialVersionUID of the javabean in the two applications must be consistent, otherwise deserialization cannot be performed normally.
/** * @description 新增套餐信息 * @author xBaozi * @date 17:55 2022/5/13 * @param setmealDto 需要新增套餐的数据 **/ @CacheEvict(value = "setmealCache",allEntries = true) @PostMapping public Result<String> save(@RequestBody SetmealDto setmealDto) { log.info("套餐信息为{}", setmealDto); setmealService.saveWithDish(setmealDto); return Result.success("套餐" + setmealDto.getName() + "新增成功"); }
The new attribute is called allEntries, which is a Boolean type used to indicate whether all elements in the cache need to be cleared. The default is false, which means it is not needed. If allEntries is set to true, Spring Cache will not consider the specified key. Sometimes it is more efficient to clear and cache all elements at once rather than clearing them one by one.
/** * @description 更新套餐信息并更新其关联的菜品 * @author xBaozi * @date 11:28 2022/5/14 * @param setmealDto 需要更新的套餐信息 **/ @CacheEvict(value = "setmealCache",allEntries = true) @PutMapping public Result<String> updateWithDish(@RequestBody SetmealDto setmealDto) { log.info(setmealDto.toString()); setmealService.updateWithDish(setmealDto); return Result.success("套餐修改成功"); }
代码编写完成之后,重启工程,然后访问后台管理系统,对套餐数据进行新增以及删除,而后观察Redis中的数据发现写的代码是能正常跑到!成功!
The above is the detailed content of How SpringBoot integrates Spring Cache to implement Redis caching. For more information, please follow other related articles on the PHP Chinese website!