SpringBoot中使用Redis案例詳解
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字符相互轉(zhuǎn)換-->
<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包下創(chuàng)建application.yml文件,并進(jìn)行配置
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.StdOutImpl3.將App.java改為項目名稱+Application.java(SpringBoot的核心啟動類)
- 負(fù)責(zé)初始化并啟動整個 Spring Boot 應(yīng)用
package com.jiazhong.mingxing.boot.boot052; // 1. 包聲明
import org.springframework.boot.SpringApplication; // 2. 核心類導(dǎo)入
import org.springframework.boot.autoconfigure.SpringBootApplication; // 3. 核心注解導(dǎo)入
@SpringBootApplication // 4. 核心注解(關(guān)鍵)
public class Boot052Application { // 5. 啟動類(類名通常與項目名對應(yīng))
// 6. 程序入口(main方法,JVM啟動時執(zhí)行)
public static void main(String[] args) {
// 7. 啟動Spring Boot應(yīng)用的核心方法
SpringApplication.run(Boot052Application.class, args);
}
}4.編寫bean包
- (主要用于存放實體類(也稱為 Java Bean),這些類通常用于封裝數(shù)據(jù),是應(yīng)用中數(shù)據(jù)傳遞和存儲的載體)
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包
- 定義數(shù)據(jù)庫操作接口:聲明 CRUD(增刪改查)等數(shù)據(jù)庫操作方法(如
selectById、insert、update)。 - 映射 SQL 語句:通過 XML 文件或注解方式,將接口方法與具體的 SQL 語句關(guān)聯(lián)。
- 隔離數(shù)據(jù)訪問邏輯:使 Service 層無需關(guān)注數(shù)據(jù)庫操作細(xì)節(jié),只需調(diào)用 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)是業(yè)務(wù)邏輯層的核心,負(fù)責(zé)實現(xiàn)應(yīng)用的核心業(yè)務(wù)邏輯,協(xié)調(diào)數(shù)據(jù)訪問層(Mapper)和控制層(Controller)之間的交互,是整個應(yīng)用的 “業(yè)務(wù)處理中心”。
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類型的內(nèi)容
List<Student> findAll1();
//Redis存儲List類型的內(nèi)容
List<Student> findAll2();
List<Student> findAll3();
//添加學(xué)生信息
int saveStudent(Student student);
//修改學(xué)生信息
int updateStudent(Student student);
//刪除學(xué)生信息
int removeStudent(String id);
}7.編寫service報下的實現(xiàn)類
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//構(gòu)造器
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:{}的數(shù)據(jù)",id);
//1.從Redis中獲取到指定id的數(shù)據(jù)
String studentJSON = forValue.get(PREFIX_STUDENT + id);
log.info("返回id:{}的數(shù)據(jù):{}",id,studentJSON);
//2.如果存在,返回該數(shù)據(jù)
if (studentJSON!=null){
log.info("存在該數(shù)據(jù),結(jié)束!");
return JSONArray.parseObject(studentJSON, Student.class);
}
//3.如果不存在該數(shù)據(jù),從數(shù)據(jù)庫中獲取
Student student = studentMapper.selectById(id);
log.info("不存在該數(shù)據(jù),從數(shù)據(jù)庫中獲取到數(shù)據(jù):{}",student);
//4.存放到Redis中
String jsonString = JSONArray.toJSONString(student);
forValue.set(PREFIX_STUDENT+id,jsonString,1, TimeUnit.HOURS);
log.info("存放數(shù)據(jù)到Redis中");
//5.返回數(shù)據(jù)
return student;
}
@Override
public List<Student> findAll1() {
//1.從Redis中獲取
String json = forValue.get(ALL_STUDENT);
//2.如果存在,返回數(shù)據(jù),結(jié)束
if (json!=null){
return JSONArray.parseArray(json, Student.class);
}
//3.如果不存在,連接數(shù)據(jù)庫
List<Student> all_student = this.list();
//4.將數(shù)據(jù)存放到Redis中
String jsonString = JSONArray.toJSONString(all_student);
forValue.set(ALL_STUDENT,jsonString,1, TimeUnit.HOURS);
//5.返回數(shù)據(jù)
return all_student;
}
@Override
public List<Student> findAll2() {
//1.從Redis中獲取
List<String> stringList = forList.range(ALL_STUDENT, 0, -1);
//2.如果存在,返回數(shù)據(jù),結(jié)束
if (stringList!=null && !stringList.isEmpty()){
List<Student> all_student=new ArrayList<>();//產(chǎn)生空集合
stringList.forEach(s -> {
Student student=JSONArray.parseObject(s,Student.class);
all_student.add(student);
});
return all_student;
}
//3.如果不存在,連接數(shù)據(jù)庫
List<Student> list = this.list();
//4.將數(shù)據(jù)存放到Redis中(一個一個的轉(zhuǎn)成JSON字符串,然后放到列表中)
list.forEach(student -> {
String s = JSONArray.toJSONString(student);
forList.rightPush(ALL_STUDENT,s);
});
//5.返回數(shù)據(jù)
return list;
}
@Override
public List<Student> findAll3() {
//1.從Redis中獲取數(shù)據(jù)
List<String> stringList = forList.range(ALL_STUDENT, 0, -1);
//2.如果存在返回數(shù)據(jù)結(jié)果
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.如果數(shù)據(jù)不存在,連接數(shù)據(jù)庫
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.返回數(shù)據(jù)
return list;
}
@Override
public int saveStudent(Student student) {
//1.將數(shù)據(jù)添加到數(shù)據(jù)庫中
boolean b = this.save(student);
//2.將剛才錄入到數(shù)據(jù)庫的數(shù)據(jù)查詢出來
QueryWrapper<Student> queryWrapper=new QueryWrapper<>();
queryWrapper.eq("name",student.getName());
queryWrapper.eq("stu_no",student.getStuNo());
Student one=getOne(queryWrapper);
//3.將數(shù)據(jù)添加到緩存中
//3.1 將one存放到String中
forValue.set(one.getId()+"",JSONArray.toJSONString(one));
//3.2 將id存放到索引區(qū)list
forList.rightPush(ALL_STUDENT,one.getId()+"");
return b?1:0;
}
/*@Override
public int saveStudent(Student student) {
//1.將數(shù)據(jù)添加到數(shù)據(jù)庫中
boolean b = this.save(student);
//2.將剛才錄入到數(shù)據(jù)庫的數(shù)據(jù)查詢出來
QueryWrapper<Student> queryWrapper=new QueryWrapper<>();
queryWrapper.eq("name",student.getName());
queryWrapper.eq("stu_no",student.getStuNo());
Student one=getOne(queryWrapper);
//3.將數(shù)據(jù)添加到緩存中
String s = JSONArray.toJSONString(one);
forList.rightPush(ALL_STUDENT,s);
return b?1:0;
}*/
@Override
public int updateStudent(Student student) {
//1.修改數(shù)據(jù)庫數(shù)據(jù)
boolean b = updateById(student);
//2.取出剛修改的數(shù)據(jù)
QueryWrapper<Student> queryWrapper=new QueryWrapper<>();
queryWrapper.eq("id",student.getId());
Student sqlStudent=getOne(queryWrapper);
//3.修改Redis緩存中的數(shù)據(jù)
forValue.setIfPresent(sqlStudent.getId()+"",JSONArray.toJSONString(sqlStudent));
return 0;
}
@Override
public int removeStudent(String id) {
//1.刪除數(shù)據(jù)庫中的數(shù)據(jù)
boolean b = removeById(id);
//2.刪除Redis緩存中的數(shù)據(jù)
forList.remove(ALL_STUDENT,1,id+"");
stringRedisTemplate.delete(id+"");
//3.返回結(jié)果
return b?1:0;
}
/*@Override
public int updateStudent(Student student) {
//1.修改數(shù)據(jù)庫中的數(shù)據(jù)
boolean update = updateById(student);
//2.取出剛修改的數(shù)據(jù)
QueryWrapper<Student> queryWrapper=new QueryWrapper<>();
queryWrapper.eq("id",student.getId());
Student sqlStudent=getOne(queryWrapper);
//3.修改Redis緩存中的數(shù)據(jù)
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
//根據(jù)id查詢學(xué)生信息
public void a(){
Student studentById = studentService.findStudentById("1966797153254133762");
log.info("studentById:{}",studentById);
}
@Test
//查詢所有學(xué)生信息
public void b1(){
List<Student> allstudent = studentService.findAll1();
log.info("allstudent:{}",allstudent);
}
@Test
//查詢所有學(xué)生信息(存儲List類型的內(nèi)容)
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
//添加學(xué)生信息
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
//修改學(xué)生信息
public void d(){
Student student = new Student();
student.setId(1966797153254133762L);
student.setBirthday("2005-3-16");
studentService.updateStudent(student);
}
@Test
//刪除學(xué)生信息
public void e(){
int i = studentService.removeStudent("1967044502643716098");
log.info("i:{}",i);
}
}到此這篇關(guān)于SpringBoot中使用Redis(引入案例)的文章就介紹到這了,更多相關(guān)SpringBoot使用Redis內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- springboot項目redis緩存異常實戰(zhàn)案例詳解(提供解決方案)
- SpringBoot 整合Redisson重寫cacheName支持多參數(shù)的案例代碼
- springboot整合ehcache和redis實現(xiàn)多級緩存實戰(zhàn)案例
- 關(guān)于SpringBoot集成Lettuce連接Redis的方法和案例
- SpringBoot如何監(jiān)聽redis?Key變化事件案例詳解
- 基于Redis結(jié)合SpringBoot的秒殺案例詳解
- springBoot整合redis使用案例詳解
- SpringBoot使用Redis同時執(zhí)行多條命令的實現(xiàn)方法
相關(guān)文章
SpringBoot使用Redis單機(jī)版過期鍵監(jiān)聽事件的實現(xiàn)示例
在緩存的使用場景中經(jīng)常需要使用到過期事件,本文主要介紹了SpringBoot使用Redis單機(jī)版過期鍵監(jiān)聽事件的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-07-07
springboot 自定義LocaleResolver實現(xiàn)切換語言
我們在做項目的時候,往往有很多項目需要根據(jù)用戶的需要來切換不同的語言,使用國際化就可以輕松解決。這篇文章主要介紹了springboot 自定義LocaleResolver切換語言,需要的朋友可以參考下2019-10-10
快速入門介紹Java中強(qiáng)大的String.format()
這篇文章主要給大家介紹了如何快速入門介紹Java中強(qiáng)大的String.format()的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-03-03
MybatisPlus創(chuàng)建時間不想用默認(rèn)值的問題
MybatisPlus通過FieldFill注解和MpMetaObjectHandler類支持自動填充字段功能,特別地,可以設(shè)置字段在插入或更新時自動填充創(chuàng)建時間和更新時間,但在特定場景下,如導(dǎo)入數(shù)據(jù)時,可能需要自定義創(chuàng)建時間2024-09-09
SpringBoot使用Maven打包后運(yùn)行失敗的問題解決詳解
在使用 Spring Boot 開發(fā)項目時,我們通常會使用 Maven 作為構(gòu)建工具,但有時會出現(xiàn)運(yùn)行失敗的情況,本文將從多個角度分析常見錯誤場景,并提供詳細(xì)的排查和解決方案,希望對大家有所幫助2025-07-07
springboot下mybatis-plus開啟打印sql日志的配置指南
這篇文章主要給大家介紹了關(guān)于springboot下mybatis-plus開啟打印sql日志的配置指南的相關(guān)資料,還介紹了關(guān)閉打印的方法,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-03-03
SpringBoot中webSocket實現(xiàn)即時聊天
這篇文章主要介紹了SpringBoot中webSocket實現(xiàn)即時聊天,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
Java+Selenium調(diào)用JavaScript的方法詳解
這篇文章主要為大家講解了java在利用Selenium操作瀏覽器網(wǎng)站時候,有時會需要用的JavaScript的地方,代碼該如何實現(xiàn)呢?快跟隨小編一起學(xué)習(xí)一下吧2023-01-01

