SpringBoot中使用Redis案例详解

 更新时间:2025年10月11日 10:10:50   作者:wangmengxxw  
文章主要介绍了在SpringBoot项目中的基本配置和文件结构,通过引入案例给大家介绍的非常详细,感兴趣的朋友一起看看吧

1.配置xml文件

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
            <version>3.5.12</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-3-starter</artifactId>
            <version>1.2.20</version>
        </dependency>
        <!--对象和JSON字符相互转换-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.32</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
    </dependencies>

2.在resources包下创建application.yml文件,并进行配置

spring:
  data:
    redis:
      host: 192.168.11.88//自己Redis的IP地址
      port: 6379
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test_db1
    username: root
    password: 123456
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

3.将App.java改为项目名称+Application.java(SpringBoot的核心启动类)

  • 负责初始化并启动整个 Spring Boot 应用
package com.jiazhong.mingxing.boot.boot052; // 1. 包声明
import org.springframework.boot.SpringApplication; // 2. 核心类导入
import org.springframework.boot.autoconfigure.SpringBootApplication; // 3. 核心注解导入
@SpringBootApplication // 4. 核心注解(关键)
public class Boot052Application { // 5. 启动类(类名通常与项目名对应)
    // 6. 程序入口(main方法,JVM启动时执行)
    public static void main(String[] args) {
        // 7. 启动Spring Boot应用的核心方法
        SpringApplication.run(Boot052Application.class, args);
    }
}

4.编写bean包

  • (主要用于存放实体类(也称为 Java Bean),这些类通常用于封装数据,是应用中数据传递和存储的载体)
package com.jiazhong.mingxing.boot.boot052.bean;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class Student {
    @TableId(value = "id")
    private Long id;
    private String name;
    private String stuNo;
    private String password;
    private Character gender;
    private String birthday;
    private String placeOfOrigin;
    private String createTime;
    private Long schoolId;
    private Long courseId;
    @TableLogic(delval = "1",value = "0")
    private Integer state;
    private String enrollmentDate;
    private String updateTime;
}

5.编写mapper包

  1. 定义数据库操作接口:声明 CRUD(增删改查)等数据库操作方法(如selectByIdinsertupdate)。
  2. 映射 SQL 语句:通过 XML 文件或注解方式,将接口方法与具体的 SQL 语句关联。
  3. 隔离数据访问逻辑:使 Service 层无需关注数据库操作细节,只需调用 Mapper 接口方法即可。
package com.jiazhong.mingxing.boot.boot052.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jiazhong.mingxing.boot.boot052.bean.Student;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
}

6.编写service包下的service类

  • service包(通常命名为com.xxx.service)是业务逻辑层的核心,负责实现应用的核心业务逻辑,协调数据访问层(Mapper)和控制层(Controller)之间的交互,是整个应用的 “业务处理中心”。
package com.jiazhong.mingxing.boot.boot052.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.jiazhong.mingxing.boot.boot052.bean.Student;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface StudentService extends IService<Student> {
    Student findStudentById(String id);
    //Redis存储String类型的内容
    List<Student> findAll1();
   //Redis存储List类型的内容
    List<Student> findAll2();
    List<Student> findAll3();
    //添加学生信息
    int saveStudent(Student student);
    //修改学生信息
    int updateStudent(Student student);
    //删除学生信息
    int removeStudent(String id);
}

7.编写service报下的实现类

package com.jiazhong.mingxing.boot.boot052.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiazhong.mingxing.boot.boot052.bean.Student;
import com.jiazhong.mingxing.boot.boot052.mapper.StudentMapper;
import com.jiazhong.mingxing.boot.boot052.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
   /* @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private StudentMapper studentMapper;*/
    private StringRedisTemplate stringRedisTemplate;
    private StudentMapper studentMapper;
    private ValueOperations<String,String> forValue;
    private ListOperations<String, String> forList;
    public static final String PREFIX_STUDENT="PREFIX_STUDENT";
    public static final String ALL_STUDENT="ALL_STUDENT";
    @Autowired//构造器
    public StudentServiceImpl(StringRedisTemplate stringRedisTemplate, StudentMapper studentMapper) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.studentMapper = studentMapper;
        this.forValue=stringRedisTemplate.opsForValue();
        this.forList=stringRedisTemplate.opsForList();
    }
    @Override
    public Student findStudentById(String id) {
        log.info("开始查询id:{}的数据",id);
        //1.从Redis中获取到指定id的数据
        String studentJSON = forValue.get(PREFIX_STUDENT + id);
        log.info("返回id:{}的数据:{}",id,studentJSON);
        //2.如果存在,返回该数据
        if (studentJSON!=null){
            log.info("存在该数据,结束!");
            return JSONArray.parseObject(studentJSON, Student.class);
        }
        //3.如果不存在该数据,从数据库中获取
        Student student = studentMapper.selectById(id);
        log.info("不存在该数据,从数据库中获取到数据:{}",student);
        //4.存放到Redis中
        String jsonString = JSONArray.toJSONString(student);
        forValue.set(PREFIX_STUDENT+id,jsonString,1, TimeUnit.HOURS);
        log.info("存放数据到Redis中");
        //5.返回数据
        return student;
    }
    @Override
    public List<Student> findAll1() {
        //1.从Redis中获取
        String json = forValue.get(ALL_STUDENT);
        //2.如果存在,返回数据,结束
        if (json!=null){
            return JSONArray.parseArray(json, Student.class);
        }
        //3.如果不存在,连接数据库
        List<Student> all_student = this.list();
        //4.将数据存放到Redis中
        String jsonString = JSONArray.toJSONString(all_student);
        forValue.set(ALL_STUDENT,jsonString,1, TimeUnit.HOURS);
        //5.返回数据
        return all_student;
    }
    @Override
    public List<Student> findAll2() {
        //1.从Redis中获取
        List<String> stringList = forList.range(ALL_STUDENT, 0, -1);
        //2.如果存在,返回数据,结束
        if (stringList!=null && !stringList.isEmpty()){
            List<Student> all_student=new ArrayList<>();//产生空集合
            stringList.forEach(s -> {
                Student student=JSONArray.parseObject(s,Student.class);
                all_student.add(student);
            });
            return all_student;
        }
        //3.如果不存在,连接数据库
        List<Student> list = this.list();
        //4.将数据存放到Redis中(一个一个的转成JSON字符串,然后放到列表中)
        list.forEach(student -> {
            String s = JSONArray.toJSONString(student);
            forList.rightPush(ALL_STUDENT,s);
        });
        //5.返回数据
        return list;
    }
    @Override
    public List<Student> findAll3() {
        //1.从Redis中获取数据
        List<String> stringList = forList.range(ALL_STUDENT, 0, -1);
        //2.如果存在返回数据结果
        if (stringList!=null && !stringList.isEmpty()){
            List<Student> all_students = new ArrayList<>();
            stringList.forEach(id -> {
                String json = forValue.get(id);
                Student student = JSONArray.parseObject(json, Student.class);
                all_students.add(student);
            });
            return all_students;
        }
        //3.如果数据不存在,连接数据库
        List<Student> list=this.list();
        //4.将对象存放到Redis中
        list.forEach(student -> {
            //4.1将id存放到集合中
            forList.rightPush(ALL_STUDENT,student.getId()+"");
            //4.2将对象存放到了String中
            forValue.set(student.getId()+"",JSONArray.toJSONString(student));
        });
        //5.返回数据
        return list;
    }
    @Override
    public int saveStudent(Student student) {
        //1.将数据添加到数据库中
        boolean b = this.save(student);
        //2.将刚才录入到数据库的数据查询出来
        QueryWrapper<Student> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("name",student.getName());
        queryWrapper.eq("stu_no",student.getStuNo());
        Student one=getOne(queryWrapper);
        //3.将数据添加到缓存中
        //3.1 将one存放到String中
        forValue.set(one.getId()+"",JSONArray.toJSONString(one));
        //3.2 将id存放到索引区list
        forList.rightPush(ALL_STUDENT,one.getId()+"");
        return b?1:0;
    }
    /*@Override
    public int saveStudent(Student student) {
        //1.将数据添加到数据库中
        boolean b = this.save(student);
        //2.将刚才录入到数据库的数据查询出来
        QueryWrapper<Student> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("name",student.getName());
        queryWrapper.eq("stu_no",student.getStuNo());
        Student one=getOne(queryWrapper);
        //3.将数据添加到缓存中
        String s = JSONArray.toJSONString(one);
        forList.rightPush(ALL_STUDENT,s);
        return b?1:0;
    }*/
    @Override
    public int updateStudent(Student student) {
        //1.修改数据库数据
        boolean b = updateById(student);
        //2.取出刚修改的数据
        QueryWrapper<Student> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",student.getId());
        Student sqlStudent=getOne(queryWrapper);
        //3.修改Redis缓存中的数据
        forValue.setIfPresent(sqlStudent.getId()+"",JSONArray.toJSONString(sqlStudent));
        return 0;
    }
    @Override
    public int removeStudent(String id) {
        //1.删除数据库中的数据
        boolean b = removeById(id);
        //2.删除Redis缓存中的数据
        forList.remove(ALL_STUDENT,1,id+"");
        stringRedisTemplate.delete(id+"");
        //3.返回结果
        return b?1:0;
    }
    /*@Override
    public int updateStudent(Student student) {
        //1.修改数据库中的数据
        boolean update = updateById(student);
        //2.取出刚修改的数据
        QueryWrapper<Student> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",student.getId());
        Student sqlStudent=getOne(queryWrapper);
        //3.修改Redis缓存中的数据
        List<String> stringList = forList.range(ALL_STUDENT, 0, -1);
        if (stringList!=null && !stringList.isEmpty()){
            final int[] index={0};
            stringList.forEach(s->{
                Student one=JSONArray.parseObject(s,Student.class);
                if (one.getId().equals(student.getId())){
                    forList.set(ALL_STUDENT,index[0],JSONArray.toJSONString(sqlStudent));
                    index[0]++;
                }
            });
        }
        return update?1:0;
    }*/
}

8.测试

package com.jiazhong.mingxing.boot.boot052.test;
import com.jiazhong.mingxing.boot.boot052.bean.Student;
import com.jiazhong.mingxing.boot.boot052.service.StudentService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
@Slf4j
public class App {
    @Resource
    private StudentService studentService;
    @Test
    //根据id查询学生信息
    public void a(){
        Student studentById = studentService.findStudentById("1966797153254133762");
        log.info("studentById:{}",studentById);
    }
    @Test
    //查询所有学生信息
    public void b1(){
        List<Student> allstudent = studentService.findAll1();
        log.info("allstudent:{}",allstudent);
    }
    @Test
    //查询所有学生信息(存储List类型的内容)
    public void b2(){
        List<Student> allstudent = studentService.findAll2();
        allstudent.forEach(e->{
            log.info("e:{}",e);
        });
    }
    @Test
    public void b3(){
        List<Student> allstudent = studentService.findAll3();
        allstudent.forEach(e->{
            log.info("e:{}",e);
        });
    }
    @Test
    //添加学生信息
    public void c(){
        Student student = new Student();
        student.setName("许锦阳");
        student.setPlaceOfOrigin("陕西咸阳");
        student.setCourseId(1965250158253547036L);
        student.setSchoolId(1965321181514842113L);
        student.setBirthday("2004-9-19");
        student.setStuNo("JK202502287783");
        student.setGender('男');
        int i = studentService.saveStudent(student);
        log.info("i:{}",i);
    }
    @Test
    //修改学生信息
    public void d(){
        Student student = new Student();
        student.setId(1966797153254133762L);
        student.setBirthday("2005-3-16");
        studentService.updateStudent(student);
    }
    @Test
    //删除学生信息
    public void e(){
        int i = studentService.removeStudent("1967044502643716098");
        log.info("i:{}",i);
    }
}

到此这篇关于SpringBoot中使用Redis(引入案例)的文章就介绍到这了,更多相关SpringBoot使用Redis内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • SpringBoot使用Redis单机版过期键监听事件的实现示例

    SpringBoot使用Redis单机版过期键监听事件的实现示例

    在缓存的使用场景中经常需要使用到过期事件,本文主要介绍了SpringBoot使用Redis单机版过期键监听事件的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-07-07
  • springboot 自定义LocaleResolver实现切换语言

    springboot 自定义LocaleResolver实现切换语言

    我们在做项目的时候,往往有很多项目需要根据用户的需要来切换不同的语言,使用国际化就可以轻松解决。这篇文章主要介绍了springboot 自定义LocaleResolver切换语言,需要的朋友可以参考下
    2019-10-10
  • 详解IDEA自定义注释模板(javadoc)

    详解IDEA自定义注释模板(javadoc)

    这篇文章主要介绍了详解IDEA自定义注释模板(javadoc),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-04-04
  • 快速入门介绍Java中强大的String.format()

    快速入门介绍Java中强大的String.format()

    这篇文章主要给大家介绍了如何快速入门介绍Java中强大的String.format()的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。
    2018-03-03
  • MybatisPlus创建时间不想用默认值的问题

    MybatisPlus创建时间不想用默认值的问题

    MybatisPlus通过FieldFill注解和MpMetaObjectHandler类支持自动填充字段功能,特别地,可以设置字段在插入或更新时自动填充创建时间和更新时间,但在特定场景下,如导入数据时,可能需要自定义创建时间
    2024-09-09
  • SpringBoot使用Maven打包后运行失败的问题解决详解

    SpringBoot使用Maven打包后运行失败的问题解决详解

    在使用 Spring Boot 开发项目时,我们通常会使用 Maven 作为构建工具,但有时会出现运行失败的情况,本文将从多个角度分析常见错误场景,并提供详细的排查和解决方案,希望对大家有所帮助
    2025-07-07
  • springboot下mybatis-plus开启打印sql日志的配置指南

    springboot下mybatis-plus开启打印sql日志的配置指南

    这篇文章主要给大家介绍了关于springboot下mybatis-plus开启打印sql日志的配置指南的相关资料,还介绍了关闭打印的方法,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2023-03-03
  • 深入理解Java中的接口

    深入理解Java中的接口

    下面小编就为大家带来一篇深入理解Java中的接口。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-05-05
  • SpringBoot中webSocket实现即时聊天

    SpringBoot中webSocket实现即时聊天

    这篇文章主要介绍了SpringBoot中webSocket实现即时聊天,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-04-04
  • Java+Selenium调用JavaScript的方法详解

    Java+Selenium调用JavaScript的方法详解

    这篇文章主要为大家讲解了java在利用Selenium操作浏览器网站时候,有时会需要用的JavaScript的地方,代码该如何实现呢?快跟随小编一起学习一下吧
    2023-01-01

最新评论