java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot使用Redis

SpringBoot中使用Redis案例详解

作者: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的核心启动类)

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包

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类

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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文