Spring Boot | Spring Boot 实现 “Redis缓存管理“

目录 :


在这里插入图片描述

作者简介 :一只大皮卡丘,计算机专业学生,正在努力学习、努力敲代码中! 让我们一起继续努力学习!

该文章参考学习教材为:
《Spring Boot企业级开发教程》 黑马程序员 / 编著
文章以课本知识点 + 代码为主线,结合自己看书学习过程中的理解和感悟 ,最终成就了该文章

文章用于本人学习使用 , 同时希望能帮助大家。
欢迎大家点赞👍 收藏⭐ 关注💖哦!!!

(侵权可联系我,进行删除,如果雷同,纯属巧合)


Spring Boot 实现 “Redis缓存管理” :

一、Spring Boot 支持的 “缓存组件” ( 如果 “没有” 明确指定使用自定义的 "cacheManager "或 “cacheResolver” ,此时 SpringBoot会按照“预先定义的顺序” 启动一个默认的 “缓存组件” 来进行 “缓存管理” )

  • Spring Boot 中,数据的 "管理存储"依赖于 Spring 框架中 cache ( 缓存 ) 相关的 :
    org.springframework.cache.
    Cache

    org.springframework,cache.CacheManager ( 缓存管理器 )。

  • 如果程序中 没有 定义类型cacheManager ( 缓存管理器 ) 的 Bean 组件或者是 没有 名为 cacheResolver ( 缓存解析器 ) ,
    Spring Boot按照以下的顺序选择并启动 缓存组件

  • 选择并启用以下缓存组件( 按照指定的顺序 ) :

    Generic

    JCache (JSR -107 ) ( EhCache 3HazelcastInfinispan等 )

    EhCache 2.x

    Hazelcast

    (5) Infinispan

    (6) Couchbase

    (7) Redis

    (8) Caffeine

    (9) Simple ( 默认"缓存组件" , SpringBoot 默认使用该“缓存组件” 来 进行 “缓存管理” )


    上面我们按照 Spring Boot 缓存组件加载顺序 列举了 支持的9种缓存组件,在项目中 添加某个缓存管理组件 (例如 Redis) Spring Boot 项目会
    选择并启用对应的缓存管理器

  • 如果项目中 同时添加多个缓存组件,且 没有指定缓存管理器 /缓存解析器( cacheManager/cacheResolver ),那么 Spring Boot 按照 “指定的顺序” 来 选择使用 其中的一个 “缓存组件” 并进行“缓存管理” 。

  • Spring Boot默认的 “缓存管理” 项目 文章讲解Spring Boot默认缓存管理中,没有添加 任何缓存管理组件却能实现缓存管理。这是因为开启缓存管理后
    如果 没有指定具体的"cacheManager "或 “cacheResolver,SpringBoot 将按照 指定的顺序选择并使用缓存组件” 。

  • 如果没有任何缓存组件,会 默认使用最后一个Simple 缓存组件进行管理Simple 缓存组件Spring Boot默认缓存管理组件,它默认使用内存ConcurrentHashMap 进行 缓存存储,所以在没有添加任何第三方缓存组件的情况下也可以实现内存中的缓存管理

二、基于 “注解” 的 “Redis缓存管理” :

① 准备数据

先创建了一个 数据库springbootdata,然后创建了两个表 t_articlet_comment ,并向表中插入数据。
其中评论表t_commenta_id 与文章表t_article主键id 相关联 ( t_article主键作为t_comment表外键)。

springbootdata.sql

② 创建项目 + 开启Mysql服务 + 开启Redis服务
  • 在这里插入图片描述


    项目目录结构 为 :
    在这里插入图片描述

③ 在配置"全局配置文件" 中 “配置信息”
  • 在配置"全局配置文件" : application.properties 中 “配置信息” :

    application.properties

    # mysql服务信息
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT&nullCatalogMeansCurrent=true
    spring.datasource.username=root
    spring.datasource.password=root
    
    
    #使用JPA操作数据库时,在控制台上显示sql语句
    spring.jpa.show-sql=true
    
    #Redis服务地址
    spring.data.redis.host=127.0.0.1
    #Redis服务器连接端口
    spring.data.redis.port=6379
    #Reids服务器连接密码(默认为空)
    spring.data.redis.password=123456
    
    #对基于注解的Redis缓存数据统一设置"有效期"为 1分钟,单位为"毫秒"
    spring.cache.redis.time-to-live= 60000
    
④ 在配置"主程序启动类" 中开启 “基于注解” 的 “缓存支持”
  • 在配置"主程序启动类" 中开启 “基于注解” 的 “缓存支持


    在这里插入图片描述

    Chapter19Application.properties

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cache.annotation.EnableCaching;
    
    @SpringBootApplication
    @EnableCaching //开启 基于 注解的缓存支持
    public class Chapter19Application {
    
        public static void main(String[] args) {
            SpringApplication.run(Chapter19Application.class, args);
        }
    
    }
    
⑤ 编写 “数据库表” 对应的 “实体类” ( 要实现"序列化" )
  • 编写 “数据库表” 对应的 “实体类” ( 要实现"序列化" ) :

    Comment.java

    import jakarta.persistence.*;
    
    import java.io.Serializable;
    
    //指定该实现类映射的数据库表
    @Entity(name = "t_Comment") //设置ORM实体类, 并指定对应的表明
    /*
       SpringBoot中的 Redis缓存管理 默认情况下使用的序列化机制为: JDK序列化机制
       ①JDK序列化机制需要在实体类中实现 Serializable序列化接口
     */
    public class Comment implements Serializable { // implements Serializable : 进行序列化,存储数据进Redis数据库时需要
    
        //表示数据库表中主键对应的属性
        @Id
        @GeneratedValue(strategy= GenerationType.IDENTITY) //设置主键的生成策略 (主键自增)
        private Integer id;
    
        @Column(name = "content") //指定映射的表字段名
        private String content;
    
        @Column(name = "author")
        private String author;
    
        @Column(name = "a_id")
        private Integer aId;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getContent() {
            return content;
        }
    
        public void setContent(String content) {
            this.content = content;
        }
    
        public String getAuthor() {
            return author;
        }
    
        public void setAuthor(String author) {
            this.author = author;
        }
    
        public Integer getaId() {
            return aId;
        }
    
        public void setaId(Integer aId) {
            this.aId = aId;
        }
    
        @Override
        public String toString() {
            return "Comment{" +
                    "id=" + id +
                    ", content='" + content + '\'' +
                    ", author='" + author + '\'' +
                    ", aId=" + aId +
                    '}';
        }
    }
    
⑥ 编写 “操作数据库” 的 Repository接口文件 ( 通过该接口中的方法来 操作“Mysql数据库” )
  • 编写 “操作数据库” 的 Repository接口文件 :

    CommentRepository.java

    import com.myh.chapter_17.domain.Comment;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.data.jpa.repository.Query;
    
    //Repository接口中为操作数据库的方法
    /*
      继承了JpaRepository接口,其中有操作数据库的curd方法,也用方法关键字的形式来操作数据库,或者使用@Query注解的方式来操作数据库
     */
    public interface CommentRepository extends JpaRepository<Comment,Integer> {
    
    }
    
⑦ 编写 "控制器层"的 controller 对象
  • 编写 "控制器层"的 controller 对象 :

    CommentController.java

    import com.myh.chapter_19.domain.Comment;
    import com.myh.chapter_19.service.CommentService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.RestController;
    
    
    @Controller //将该类加入到IOC容器中
    @ResponseBody //将方法的返回值转换为指定的类型 存储到响应体中
    public class CommentController { //控制层操作类
    
        @Autowired
        private CommentService commentService;
    
        /**
         * 查询数据
         */
        @GetMapping("/findById/{id}") //传递的参数为: 路径变量
        public Comment findById(@PathVariable("id")  int comment_id) {
            Comment comment = commentService.findById(comment_id);
            return comment;
        }
    
    
        /**
         * 更新数据
         */
        @GetMapping("/updateComment/{id}/{author}")
        public Comment updateComment(@PathVariable("id")  int comment_id,@PathVariable("author")  String author) {
            Comment comment = commentService.updateComment(comment_id, author);
            return comment;
        }
    
        /**
         * 删除数据
         */
        @GetMapping("/deleteComment/{id}")
        public void deleteComment(@PathVariable("id")  int comment_id) {
            commentService.deleteComment(comment_id);
        }
    
    }
    
⑧ 编写 "业务操作层"的 service 对象
  • 编写 "业务操作层"的 service 对象 :

    CommentService.java

    import com.myh.chapter_19.domain.Comment;
    import com.myh.chapter_19.repository.CommentRepository;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.cache.annotation.CacheEvict;
    import org.springframework.cache.annotation.CachePut;
    import org.springframework.cache.annotation.Cacheable;
    import org.springframework.stereotype.Service;
    
    import java.util.Optional;
    
    @Service //加入到ioc容器中
    public class CommentService {
    
        @Autowired
        private CommentRepository commentRepository;
    
        /**
         * 查询数据
         */
        @Cacheable(cacheNames = "comment",key = "#comment_id")
        public Comment findById(int comment_id) {
            Optional<Comment> option = commentRepository.findById(comment_id);
            //判断其中是否有数据
            if (option.isPresent()) {
                //获得该数据
                return  option.get();
            }
            return null;
        }
    
        /**
         *  更新数据
         */
        @CachePut(cacheNames = "comment",key = "#result.id") //key为更新的结果的主键id
        public Comment updateComment(int commentId, String author) {
            Comment comment = findById(commentId);
            comment.setAuthor(author);
    
            comment = commentRepository.save(comment);
            return comment;
        }
    
        /**
         *  删除数据
         */
        @CacheEvict(cacheNames = "comment",key = "#commentId") //用SpEL表达式来赋值
        public void deleteComment(int commentId) {
            System.out.println("指定id的数据库数据删除成功!");
            //commentRepository.deleteById(commentId);
        }
    }
    
⑨ 基于 “注解” 的 “缓存管理” 测试
  • 基于"注解" 的 “缓存管理” 测试 :
    访问 controller类 中的 url进行测试即可


    启动项目访问成功后可以在Redis可视化界面 上看到存储的”缓存数据 , 如下图所示

    在这里插入图片描述

三、基于 “API” ( RedisTemplate类 ) 的 “Redis缓存管理”

  • SpringBoot 整合 Redis 缓存实现中,除了基于注解形式Redis 缓存实现外,还有一个开发中常用的方式基于 “API” 的 “Redis缓存实现” ,下面将通过 Redis API 的方式讲解 SpringBoot 整合 Redis缓存具体实现

31. "RedisTemplate类"的 功能介绍 ( 通过该类可以在Java中 "操作Redis数据库 " )

  • RedisTemplate类 ( Redis模板类 )是 Spring 框架提供的用于与 Redis 数据库进行交互工具类 ( 通过 该类 可以在 Java 中 "操作Redis数据库 " ) 。
  • RedisTemplate 类Spring Data Redis 提供的 直接进行Redis操作Java API ( 通过该操作Redis数据库 ),可以直接注入使用,相比于Jedis 更加简便
  • RedisTemplate 可以 操作 <Object,Object >对象类型 数据,而其子类 StringRedisTemplate则是专门针对<String,String>字符串类型 的数据进行操作
  • RedisTemplate 类中提供了很多操作Redis数据库方法, 可以进行数据缓存查询缓存更新缓存修改缓存删除以及设置缓存有效期等。

3.2 基于 “API” ( RedisTemplate类 ) 的 “Redis缓存管理” - 案例演示 :

① 准备数据

先创建了一个 数据库springbootdata,然后创建了两个表 t_articlet_comment ,并向表中插入数据。
其中评论表t_commenta_id 与文章表t_article主键id 相关联 ( t_article主键作为t_comment表外键)。

springbootdata.sql

② 创建项目 + 开启Mysql服务 + 开启Redis服务
  • 在这里插入图片描述


    项目目录结构 为 :
    在这里插入图片描述

③ 在配置"全局配置文件" 中 “配置信息”
  • 在配置"全局配置文件" : application.properties 中 “配置信息” :

    application.properties

    # mysql服务信息
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT&nullCatalogMeansCurrent=true
    spring.datasource.username=root
    spring.datasource.password=root
    
    #使用JPA操作数据库时,在控制台上显示sql语句
    spring.jpa.show-sql=true
    
    #Redis服务地址
    spring.data.redis.host=127.0.0.1
    #Redis服务器连接端口
    spring.data.redis.port=6379
    #Reids服务器连接密码(默认为空)
    spring.data.redis.password=123456
    
④ 编写 “数据库表” 对应的 “实体类” ( 要实现"序列化" )
  • 编写 “数据库表” 对应的 “实体类” ( 要实现"序列化" ) :

    Comment.java

    import jakarta.persistence.*;
    
    import java.io.Serializable;
    
    //指定该实现类映射的数据库表
    @Entity(name = "t_Comment") //设置ORM实体类, 并指定对应的表明
    /*
       SpringBoot中的 Redis缓存管理 默认情况下使用的序列化机制为: JDK序列化机制
       ①JDK序列化机制需要在实体类中实现 Serializable序列化接口
     */
    public class Comment implements Serializable { // implements Serializable : 进行序列化,存储数据进Redis数据库时需要
    
        //表示数据库表中主键对应的属性
        @Id
        @GeneratedValue(strategy= GenerationType.IDENTITY) //设置主键的生成策略 (主键自增)
        private Integer id;
    
        @Column(name = "content") //指定映射的表字段名
        private String content;
    
        @Column(name = "author")
        private String author;
    
        @Column(name = "a_id")
        private Integer aId;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getContent() {
            return content;
        }
    
        public void setContent(String content) {
            this.content = content;
        }
    
        public String getAuthor() {
            return author;
        }
    
        public void setAuthor(String author) {
            this.author = author;
        }
    
        public Integer getaId() {
            return aId;
        }
    
        public void setaId(Integer aId) {
            this.aId = aId;
        }
    
        @Override
        public String toString() {
            return "Comment{" +
                    "id=" + id +
                    ", content='" + content + '\'' +
                    ", author='" + author + '\'' +
                    ", aId=" + aId +
                    '}';
        }
    }
    
⑤ 编写 “操作数据库” 的 Repository接口文件 ( 通过该接口中的方法来 操作“Mysql数据库” )
  • 编写 “操作数据库” 的 Repository接口文件 :

    CommentRepository.java

    import com.myh.chapter_17.domain.Comment;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.data.jpa.repository.Query;
    
    //Repository接口中为操作数据库的方法
    /*
      继承了JpaRepository接口,其中有操作数据库的curd方法,也用方法关键字的形式来操作数据库,或者使用@Query注解的方式来操作数据库
     */
    public interface CommentRepository extends JpaRepository<Comment,Integer> {
    
    }
    
⑥ 编写 "控制器层"的 controller 对象
  • 编写 "控制器层"的 controller 对象 :

    ApiCommentController.java

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;
    
    @RestController // 将该类加入到IOC容器中 + 将方法的返回值转换为指定的类型 存储到响应体中
    @RequestMapping("/api")
    public class ApiCommentController { //控制层操作类
    
        @Autowired
        private ApiCommentService apiCommentService;
    
        /**
         * 查询数据
         */
        @GetMapping("/get/{id}") //传递的参数为: 路径变量
        public Comment findById(@PathVariable("id")  int comment_id) {
            Comment comment = apiCommentService.findById(comment_id);
            return comment;
        }
    
        /**
         * 更新数据
         */
        @GetMapping("/update/{id}/{author}")
        public Comment updateComment(@PathVariable("id")  int comment_id,@PathVariable("author")  String author) {
            Comment updateComment = apiCommentService.updateComment(comment_id, author);
            return updateComment;
        }
    
        /**
         * 删除数据
         */
        @GetMapping("/delete/{id}")
        public void deleteComment(@PathVariable("id")  int comment_id) {
           apiCommentService.deleteComment(comment_id);
        }
    
    
    }
    
⑦ 编写 "业务操作层"的 service 对象
  • 编写 "业务操作层"的 service 对象 :

    ApiCommentService.java

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.ValueOperations;
    import org.springframework.stereotype.Service;
    
    import java.util.Optional;
    import java.util.concurrent.TimeUnit;
    
    @Service //加入到IOC容器中
    public class ApiCommentService { //业务操作类
    
        @Autowired
        private CommentRepository commentRepository;  //该接口继承了JPA相关的接口,通过其中的方法可操作Mysql数据库
    
        @Autowired
        private RedisTemplate redisTemplate; //通过该类可在Java中操作Redis数据库
    
        /**
           从Mysql数据库中查询到数据后,将该数据存储到缓存中 (存储到Redis数据库中 )
         */
       public Comment findById(int comment_id) {
           //从Redis数据库中获取"缓存数据"
           ValueOperations valueOperations = redisTemplate.opsForValue();
           Object object = valueOperations.get(comment_id);
           if (object != null) {//如果在Redis数据库中查询数据则返回
               return (Comment) object;
           } else {
               //Reids中(缓存中)没有,进行数据库查询
               Optional<Comment> optional = commentRepository.findById(comment_id);
               //判断从数据库中是否查询到数据
               if (optional.isPresent()) {
                   //获得该数据
                   Comment comment = optional.get();
                   //将从Mysql数据库中的查询结果进行"缓存" ( 缓存到Redis数据库中 ) , 设置有效期为1天
                   //设置的为Redis中的字符串数据
                   valueOperations.set(comment_id, comment, 1, TimeUnit.DAYS); //有效期为1天
                   return comment;
               } else {
                   return null;
               }
           }
       }
    
    
        /**
          更新Mysql数据库中的数据后,也更新缓存中的数据 (即同时也更新Redis数据库中的数据)
         */
        public Comment updateComment(int comment_id,String author) {
            Comment comment = findById(comment_id);
            comment.setAuthor(author);
            comment = commentRepository.save(comment);
    
            //更新Mysql数据库中数据后,同时也更新缓存中的数据 ( 即更新Redis中的数据 )
            ValueOperations valueOperations = redisTemplate.opsForValue();
            valueOperations.set(comment_id,comment);
    
            return comment;
        }
    
    
        /**
         * 删除Mysql数据库中数据后,也删除Redis中的缓存数据
         */
        public void deleteComment(int comment_id) {
            //commentRepository.deleteById(comment_id);
            System.out.println("Mysql数据库中对应的数据删除成功.....");
    
            //删除Mysql数据库中数据后,也删除Redis数据库中的"缓存数据"
            Boolean commentId = redisTemplate.delete(comment_id);
            if (commentId) {
                System.out.println("Redis数据库中对应的缓存数据-删除成功.....");
            }
        }
    
    }
    
⑧ 基于 API ( RedisTemplate类 ) 的 “缓存管理” 测试
  • 基于 API ( RedisTemplate类 ) 的 “缓存管理” 测试 :
    访问 controller类 中的 url进行测试即可


    启动项目访问成功后可以在Redis可视化界面 上看到存储的”缓存数据 , 如下图所示

    在这里插入图片描述

  • 30
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值