How SpringBoot integrates Spring Cache to implement Redis caching
1. Introduction
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 |
2. Common annotations
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 |
2.1, @EnableCaching
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("项目启动成功..."); } }
2.2, @Cacheable
@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; }
2.3、@CachePut
@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; }
2.4、@CacheEvict
@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; }
3. Use Redis as a caching product
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.
3.1, coordinate import
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>
3.2, yml configuration
spring:
redis:
host: localhost
port: 6379
password: 123456
database: 0
cache:
redis:
Time-to-live: 1800000 # Set the cache validity period
3.3. Enable the annotation function
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项目启动成功……"); } }
3.4. When using @Cacheable
, 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() + "新增成功"); }
3.5. Use @CacheEvict
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("套餐修改成功"); }
4、测试
代码编写完成之后,重启工程,然后访问后台管理系统,对套餐数据进行新增以及删除,而后观察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!

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

Redis improves application performance and scalability by caching data, implementing distributed locking and data persistence. 1) Cache data: Use Redis to cache frequently accessed data to improve data access speed. 2) Distributed lock: Use Redis to implement distributed locks to ensure the security of operation in a distributed environment. 3) Data persistence: Ensure data security through RDB and AOF mechanisms to prevent data loss.

Redis's data model and structure include five main types: 1. String: used to store text or binary data, and supports atomic operations. 2. List: Ordered elements collection, suitable for queues and stacks. 3. Set: Unordered unique elements set, supporting set operation. 4. Ordered Set (SortedSet): A unique set of elements with scores, suitable for rankings. 5. Hash table (Hash): a collection of key-value pairs, suitable for storing objects.

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.

Redis is a powerful database solution because it provides fast performance, rich data structures, high availability and scalability, persistence capabilities, and a wide range of ecosystem support. 1) Extremely fast performance: Redis's data is stored in memory and has extremely fast read and write speeds, suitable for high concurrency and low latency applications. 2) Rich data structure: supports multiple data types, such as lists, collections, etc., which are suitable for a variety of scenarios. 3) High availability and scalability: supports master-slave replication and cluster mode to achieve high availability and horizontal scalability. 4) Persistence and data security: Data persistence is achieved through RDB and AOF to ensure data integrity and reliability. 5) Wide ecosystem and community support: with a huge ecosystem and active community,

Key features of Redis include speed, flexibility and rich data structure support. 1) Speed: Redis is an in-memory database, and read and write operations are almost instantaneous, suitable for cache and session management. 2) Flexibility: Supports multiple data structures, such as strings, lists, collections, etc., which are suitable for complex data processing. 3) Data structure support: provides strings, lists, collections, hash tables, etc., which are suitable for different business needs.

The core function of Redis is a high-performance in-memory data storage and processing system. 1) High-speed data access: Redis stores data in memory and provides microsecond-level read and write speed. 2) Rich data structure: supports strings, lists, collections, etc., and adapts to a variety of application scenarios. 3) Persistence: Persist data to disk through RDB and AOF. 4) Publish subscription: Can be used in message queues or real-time communication systems.

Redis supports a variety of data structures, including: 1. String, suitable for storing single-value data; 2. List, suitable for queues and stacks; 3. Set, used for storing non-duplicate data; 4. Ordered Set, suitable for ranking lists and priority queues; 5. Hash table, suitable for storing object or structured data.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor