最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot中使用Redis案例詳解

 更新時(shí)間:2025年10月11日 10:10:50   作者:wangmengxxw  
文章主要介紹了在SpringBoot項(xiàng)目中的基本配置和文件結(jié)構(gòu),通過(guò)引入案例給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧

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>
        <!--對(duì)象和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.StdOutImpl

3.將App.java改為項(xiàng)目名稱+Application.java(SpringBoot的核心啟動(dòng)類(lèi))

  • 負(fù)責(zé)初始化并啟動(dòng)整個(gè) Spring Boot 應(yīng)用
package com.jiazhong.mingxing.boot.boot052; // 1. 包聲明
import org.springframework.boot.SpringApplication; // 2. 核心類(lèi)導(dǎo)入
import org.springframework.boot.autoconfigure.SpringBootApplication; // 3. 核心注解導(dǎo)入
@SpringBootApplication // 4. 核心注解(關(guān)鍵)
public class Boot052Application { // 5. 啟動(dòng)類(lèi)(類(lèi)名通常與項(xiàng)目名對(duì)應(yīng))
    // 6. 程序入口(main方法,JVM啟動(dòng)時(shí)執(zhí)行)
    public static void main(String[] args) {
        // 7. 啟動(dòng)Spring Boot應(yīng)用的核心方法
        SpringApplication.run(Boot052Application.class, args);
    }
}

4.編寫(xiě)bean包

  • (主要用于存放實(shí)體類(lèi)(也稱為 Java Bean),這些類(lèi)通常用于封裝數(shù)據(jù),是應(yīng)用中數(shù)據(jù)傳遞和存儲(chǔ)的載體)
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.編寫(xiě)mapper包

  1. 定義數(shù)據(jù)庫(kù)操作接口:聲明 CRUD(增刪改查)等數(shù)據(jù)庫(kù)操作方法(如selectById、insertupdate)。
  2. 映射 SQL 語(yǔ)句:通過(guò) XML 文件或注解方式,將接口方法與具體的 SQL 語(yǔ)句關(guān)聯(lián)。
  3. 隔離數(shù)據(jù)訪問(wèn)邏輯:使 Service 層無(wú)需關(guān)注數(shù)據(jù)庫(kù)操作細(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.編寫(xiě)service包下的service類(lèi)

  • service包(通常命名為com.xxx.service)是業(yè)務(wù)邏輯層的核心,負(fù)責(zé)實(shí)現(xiàn)應(yīng)用的核心業(yè)務(wù)邏輯,協(xié)調(diào)數(shù)據(jù)訪問(wèn)層(Mapper)和控制層(Controller)之間的交互,是整個(gè)應(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存儲(chǔ)String類(lèi)型的內(nèi)容
    List<Student> findAll1();
   //Redis存儲(chǔ)List類(lèi)型的內(nèi)容
    List<Student> findAll2();
    List<Student> findAll3();
    //添加學(xué)生信息
    int saveStudent(Student student);
    //修改學(xué)生信息
    int updateStudent(Student student);
    //刪除學(xué)生信息
    int removeStudent(String id);
}

7.編寫(xiě)service報(bào)下的實(shí)現(xiàn)類(lèi)

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("開(kāi)始查詢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ù)庫(kù)中獲取
        Student student = studentMapper.selectById(id);
        log.info("不存在該數(shù)據(jù),從數(shù)據(jù)庫(kù)中獲取到數(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.返回?cái)?shù)據(jù)
        return student;
    }
    @Override
    public List<Student> findAll1() {
        //1.從Redis中獲取
        String json = forValue.get(ALL_STUDENT);
        //2.如果存在,返回?cái)?shù)據(jù),結(jié)束
        if (json!=null){
            return JSONArray.parseArray(json, Student.class);
        }
        //3.如果不存在,連接數(shù)據(jù)庫(kù)
        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.返回?cái)?shù)據(jù)
        return all_student;
    }
    @Override
    public List<Student> findAll2() {
        //1.從Redis中獲取
        List<String> stringList = forList.range(ALL_STUDENT, 0, -1);
        //2.如果存在,返回?cái)?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ù)庫(kù)
        List<Student> list = this.list();
        //4.將數(shù)據(jù)存放到Redis中(一個(gè)一個(gè)的轉(zhuǎn)成JSON字符串,然后放到列表中)
        list.forEach(student -> {
            String s = JSONArray.toJSONString(student);
            forList.rightPush(ALL_STUDENT,s);
        });
        //5.返回?cái)?shù)據(jù)
        return list;
    }
    @Override
    public List<Student> findAll3() {
        //1.從Redis中獲取數(shù)據(jù)
        List<String> stringList = forList.range(ALL_STUDENT, 0, -1);
        //2.如果存在返回?cái)?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ù)庫(kù)
        List<Student> list=this.list();
        //4.將對(duì)象存放到Redis中
        list.forEach(student -> {
            //4.1將id存放到集合中
            forList.rightPush(ALL_STUDENT,student.getId()+"");
            //4.2將對(duì)象存放到了String中
            forValue.set(student.getId()+"",JSONArray.toJSONString(student));
        });
        //5.返回?cái)?shù)據(jù)
        return list;
    }
    @Override
    public int saveStudent(Student student) {
        //1.將數(shù)據(jù)添加到數(shù)據(jù)庫(kù)中
        boolean b = this.save(student);
        //2.將剛才錄入到數(shù)據(jù)庫(kù)的數(shù)據(jù)查詢出來(lái)
        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ù)庫(kù)中
        boolean b = this.save(student);
        //2.將剛才錄入到數(shù)據(jù)庫(kù)的數(shù)據(jù)查詢出來(lái)
        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ù)庫(kù)數(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ù)庫(kù)中的數(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ù)庫(kù)中的數(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.測(cè)試

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é)生信息(存儲(chǔ)List類(lèi)型的內(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("許錦陽(yáng)");
        student.setPlaceOfOrigin("陜西咸陽(yáng)");
        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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot使用Redis單機(jī)版過(guò)期鍵監(jiān)聽(tīng)事件的實(shí)現(xiàn)示例

    SpringBoot使用Redis單機(jī)版過(guò)期鍵監(jiān)聽(tīng)事件的實(shí)現(xiàn)示例

    在緩存的使用場(chǎng)景中經(jīng)常需要使用到過(guò)期事件,本文主要介紹了SpringBoot使用Redis單機(jī)版過(guò)期鍵監(jiān)聽(tīng)事件的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2024-07-07
  • springboot 自定義LocaleResolver實(shí)現(xiàn)切換語(yǔ)言

    springboot 自定義LocaleResolver實(shí)現(xiàn)切換語(yǔ)言

    我們?cè)谧鲰?xiàng)目的時(shí)候,往往有很多項(xiàng)目需要根據(jù)用戶的需要來(lái)切換不同的語(yǔ)言,使用國(guó)際化就可以輕松解決。這篇文章主要介紹了springboot 自定義LocaleResolver切換語(yǔ)言,需要的朋友可以參考下
    2019-10-10
  • 詳解IDEA自定義注釋模板(javadoc)

    詳解IDEA自定義注釋模板(javadoc)

    這篇文章主要介紹了詳解IDEA自定義注釋模板(javadoc),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-04-04
  • 快速入門(mén)介紹Java中強(qiáng)大的String.format()

    快速入門(mén)介紹Java中強(qiáng)大的String.format()

    這篇文章主要給大家介紹了如何快速入門(mén)介紹Java中強(qiáng)大的String.format()的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。
    2018-03-03
  • MybatisPlus創(chuàng)建時(shí)間不想用默認(rèn)值的問(wèn)題

    MybatisPlus創(chuàng)建時(shí)間不想用默認(rèn)值的問(wèn)題

    MybatisPlus通過(guò)FieldFill注解和MpMetaObjectHandler類(lèi)支持自動(dòng)填充字段功能,特別地,可以設(shè)置字段在插入或更新時(shí)自動(dòng)填充創(chuàng)建時(shí)間和更新時(shí)間,但在特定場(chǎng)景下,如導(dǎo)入數(shù)據(jù)時(shí),可能需要自定義創(chuàng)建時(shí)間
    2024-09-09
  • SpringBoot使用Maven打包后運(yùn)行失敗的問(wèn)題解決詳解

    SpringBoot使用Maven打包后運(yùn)行失敗的問(wèn)題解決詳解

    在使用 Spring Boot 開(kāi)發(fā)項(xiàng)目時(shí),我們通常會(huì)使用 Maven 作為構(gòu)建工具,但有時(shí)會(huì)出現(xiàn)運(yùn)行失敗的情況,本文將從多個(gè)角度分析常見(jiàn)錯(cuò)誤場(chǎng)景,并提供詳細(xì)的排查和解決方案,希望對(duì)大家有所幫助
    2025-07-07
  • springboot下mybatis-plus開(kāi)啟打印sql日志的配置指南

    springboot下mybatis-plus開(kāi)啟打印sql日志的配置指南

    這篇文章主要給大家介紹了關(guān)于springboot下mybatis-plus開(kāi)啟打印sql日志的配置指南的相關(guān)資料,還介紹了關(guān)閉打印的方法,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-03-03
  • 深入理解Java中的接口

    深入理解Java中的接口

    下面小編就為大家?guī)?lái)一篇深入理解Java中的接口。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2016-05-05
  • SpringBoot中webSocket實(shí)現(xiàn)即時(shí)聊天

    SpringBoot中webSocket實(shí)現(xiàn)即時(shí)聊天

    這篇文章主要介紹了SpringBoot中webSocket實(shí)現(xiàn)即時(shí)聊天,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04
  • Java+Selenium調(diào)用JavaScript的方法詳解

    Java+Selenium調(diào)用JavaScript的方法詳解

    這篇文章主要為大家講解了java在利用Selenium操作瀏覽器網(wǎng)站時(shí)候,有時(shí)會(huì)需要用的JavaScript的地方,代碼該如何實(shí)現(xiàn)呢?快跟隨小編一起學(xué)習(xí)一下吧
    2023-01-01

最新評(píng)論

佳木斯市| 衡阳县| 洪湖市| 紫阳县| 介休市| 龙游县| 南乐县| 秦皇岛市| 乌苏市| 东乡| 庆安县| 桂林市| 岳普湖县| 牡丹江市| 庄河市| 苍山县| 五大连池市| 闽侯县| 马尔康县| 临汾市| 吉安市| 乳山市| 宿州市| 垦利县| 商河县| 嘉善县| 南昌市| 灌南县| 黑龙江省| 卢湾区| 昌都县| 政和县| 黄山市| 万宁市| 兴宁市| 南丰县| 宿州市| 江孜县| 永安市| 云浮市| 河北省|