search
HomeDatabaseRedisHow SpringBoot integrates Spring Cache to implement Redis caching

How SpringBoot integrates Spring Cache to implement Redis caching

May 27, 2023 am 08:47 AM
redisspringbootspringcache

    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中的数据发现写的代码是能正常跑到!成功!

    How SpringBoot integrates Spring Cache to implement Redis caching

    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!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    Redis: Beyond SQL - The NoSQL PerspectiveRedis: Beyond SQL - The NoSQL PerspectiveMay 08, 2025 am 12:25 AM

    Redis goes beyond SQL databases because of its high performance and flexibility. 1) Redis achieves extremely fast read and write speed through memory storage. 2) It supports a variety of data structures, such as lists and collections, suitable for complex data processing. 3) Single-threaded model simplifies development, but high concurrency may become a bottleneck.

    Redis: A Comparison to Traditional Database ServersRedis: A Comparison to Traditional Database ServersMay 07, 2025 am 12:09 AM

    Redis is superior to traditional databases in high concurrency and low latency scenarios, but is not suitable for complex queries and transaction processing. 1.Redis uses memory storage, fast read and write speed, suitable for high concurrency and low latency requirements. 2. Traditional databases are based on disk, support complex queries and transaction processing, and have strong data consistency and persistence. 3. Redis is suitable as a supplement or substitute for traditional databases, but it needs to be selected according to specific business needs.

    Redis: Introduction to a Powerful In-Memory Data StoreRedis: Introduction to a Powerful In-Memory Data StoreMay 06, 2025 am 12:08 AM

    Redisisahigh-performancein-memorydatastructurestorethatexcelsinspeedandversatility.1)Itsupportsvariousdatastructureslikestrings,lists,andsets.2)Redisisanin-memorydatabasewithpersistenceoptions,ensuringfastperformanceanddatasafety.3)Itoffersatomicoper

    Is Redis Primarily a Database?Is Redis Primarily a Database?May 05, 2025 am 12:07 AM

    Redis is primarily a database, but it is more than just a database. 1. As a database, Redis supports persistence and is suitable for high-performance needs. 2. As a cache, Redis improves application response speed. 3. As a message broker, Redis supports publish-subscribe mode, suitable for real-time communication.

    Redis: Database, Server, or Something Else?Redis: Database, Server, or Something Else?May 04, 2025 am 12:08 AM

    Redisisamultifacetedtoolthatservesasadatabase,server,andmore.Itfunctionsasanin-memorydatastructurestore,supportsvariousdatastructures,andcanbeusedasacache,messagebroker,sessionstorage,andfordistributedlocking.

    Redis: Unveiling Its Purpose and Key ApplicationsRedis: Unveiling Its Purpose and Key ApplicationsMay 03, 2025 am 12:11 AM

    Redisisanopen-source,in-memorydatastructurestoreusedasadatabase,cache,andmessagebroker,excellinginspeedandversatility.Itiswidelyusedforcaching,real-timeanalytics,sessionmanagement,andleaderboardsduetoitssupportforvariousdatastructuresandfastdataacces

    Redis: A Guide to Key-Value Data StoresRedis: A Guide to Key-Value Data StoresMay 02, 2025 am 12:10 AM

    Redis is an open source memory data structure storage used as a database, cache and message broker, suitable for scenarios where fast response and high concurrency are required. 1.Redis uses memory to store data and provides microsecond read and write speed. 2. It supports a variety of data structures, such as strings, lists, collections, etc. 3. Redis realizes data persistence through RDB and AOF mechanisms. 4. Use single-threaded model and multiplexing technology to handle requests efficiently. 5. Performance optimization strategies include LRU algorithm and cluster mode.

    Redis: Caching, Session Management, and MoreRedis: Caching, Session Management, and MoreMay 01, 2025 am 12:03 AM

    Redis's functions mainly include cache, session management and other functions: 1) The cache function stores data through memory to improve reading speed, and is suitable for high-frequency access scenarios such as e-commerce websites; 2) The session management function shares session data in a distributed system and automatically cleans it through an expiration time mechanism; 3) Other functions such as publish-subscribe mode, distributed locks and counters, suitable for real-time message push and multi-threaded systems and other scenarios.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools