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: 6379datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/test_db1username: rootpassword: 123456mybatis-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包
- 定义数据库操作接口:声明 CRUD(增删改查)等数据库操作方法(如
selectById
、insert
、update
)。 - 映射 SQL 语句:通过 XML 文件或注解方式,将接口方法与具体的 SQL 语句关联。
- 隔离数据访问逻辑:使 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 {/* @Resourceprivate StringRedisTemplate stringRedisTemplate;@Resourceprivate 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();}@Overridepublic 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;}@Overridepublic 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;}@Overridepublic 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;}@Overridepublic 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;}@Overridepublic 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存放到索引区listforList.rightPush(ALL_STUDENT,one.getId()+"");return b?1:0;}/*@Overridepublic 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;}*/@Overridepublic 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;}@Overridepublic 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;}/*@Overridepublic 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 {@Resourceprivate 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);});}@Testpublic 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);}
}