SpringBoot + MySQL + MyBatis 整合 Redis 實現緩存操作


本地安裝 Redis

Redis 安裝:https://www.cnblogs.com/oukele/p/11373052.html

 

項目結構:

 SpringBootRedis 工程項目結構如下:

  controller - Controller 層

  dao - 數據操作層

  model - 實體層

  service - 業務邏輯層

  Application - 啟動類

 

  resources 資源文件夾

    application.properties - 應用配置文件,應用啟動會自動讀取配置

    generatorConfig.xml - mybatis 逆向生成配置(這里不是本文只要重點,所以不進行介紹)

    mapper 文件夾

      StudentMapper.xml - mybatis 關系映射 xml 文件

 

 項目工程代碼詳情

  pom.xml 配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <!--    web 依賴    -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--    tomcat插件    -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <!--    Test 依賴    -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- mysql 依賴  -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <!--   redis 依賴     -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.1.6.RELEASE</version>
        </dependency>
        <!--   mybatis 依賴     -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- Gson json 格式化 -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!-- mybatis.generator 插件  -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.7</version>

                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                </configuration>
                <!-- 數據庫依賴  -->
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>8.0.15</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

</project>
application.properties 配置
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb?useSSL=true
    username: oukele
    password: oukele
    driver-class-name: com.mysql.jdbc.Driver
  # 配置 redis
  redis:
    # redis 數據庫索引(默認為0)
    database: 0
    # redis 服務地址
    host: 127.0.0.1
    # redis 連接端口
    port: 6379
    # redis 服務器鏈接密碼 (默認為空)
    password:
    # 連接超時時間 (毫秒)
    timeout: 5000
    # 配置 redis 連接池
    jedis:
      pool:
        # 連接池最大連接數 (使用負值表示沒有限制)
        max-active: 8
        # 連接池最大阻塞等待時間(使用負值表示沒有限制)
        max-wait: -1
        # 連接池的最大空閑連接
        max-idle: 8
        # 連接池中 最小空閑連接
        min-idle: 0
# 配置 mybatis
mybatis:
  # 設置 實體類所在的包名
  typeAliasesPackage: com.example.demo.model
  # mybatis xml 映射關系
  mapper-locations: classpath:mapper/*.xml

項目結構圖

model 層 Student.java
package com.example.demo.model;

public class Student {
    private Integer id;

    private String numbercode;

    private String stuname;

    private String stusex;

    private Integer stuage;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getNumbercode() {
        return numbercode;
    }

    public void setNumbercode(String numbercode) {
        this.numbercode = numbercode == null ? null : numbercode.trim();
    }

    public String getStuname() {
        return stuname;
    }

    public void setStuname(String stuname) {
        this.stuname = stuname == null ? null : stuname.trim();
    }

    public String getStusex() {
        return stusex;
    }

    public void setStusex(String stusex) {
        this.stusex = stusex == null ? null : stusex.trim();
    }

    public Integer getStuage() {
        return stuage;
    }

    public void setStuage(Integer stuage) {
        this.stuage = stuage;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", numbercode='" + numbercode + '\'' +
                ", stuname='" + stuname + '\'' +
                ", stusex='" + stusex + '\'' +
                ", stuage=" + stuage +
                '}';
    }
}
View Code
dao 層 StudentMapper.java (使用了 注解 + xml 形式 )
package com.example.demo.dao;

import com.example.demo.model.Student;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface StudentMapper {

    @Select("select * from student")
    List<Student> selectAll();

    @Select("select * from student where numbercode = #{numberCode}")
    Student getStudent(@Param("numberCode") String numberCode);

    @Delete("delete from student where numbercode = #{numberCode}")
    int delete(@Param("numberCode") String numberCode);

    int update(Student student);

    int insert(Student student);
}
View Code
service 層 StudentService.java 
package com.example.demo.service;

import com.example.demo.model.Student;

import java.util.List;

public interface StudentService {

    List<Student> selectAll();

    Student getStudent(String numberCode);

    int delete(String numberCode);

    int update(Student student);

    int insert(Student student);

}
View Code  
service imple (業務實現)層 StudentServiceImpl.java 
package com.example.demo.service.impl;

import com.example.demo.dao.StudentMapper;
import com.example.demo.model.Student;
import com.example.demo.service.StudentService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.lang.reflect.Type;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<Student> selectAll() {

        String key = "student_list";
        Boolean hasKey = redisTemplate.hasKey(key);

        ValueOperations operations = redisTemplate.opsForValue();

        if (hasKey) {
            String redisList = (String) operations.get(key);

            Type type = new TypeToken<List<Student>>() {}.getType();
            List<Student> list =  new Gson().fromJson(redisList,type);

            System.out.println("StudentServiceImpl.selectAll() : 從緩存取得數據,條數:" + list.size());
            return list;
        }
        List<Student> list = studentMapper.selectAll();
        String toJson = new Gson().toJson(list);
        // 存在到緩存中
        operations.set(key, toJson, 10, TimeUnit.SECONDS);
        return list;
    }

    /**
     * 獲取 一位 學生邏輯:
     * 如果緩存存在,從緩存中獲取學生信息
     * 如果緩存不存在,從 DB 中獲取學生信息,然后插入緩存
     */
    @Override
    public Student getStudent(String numberCode) {
        // 從緩存中 取出學生信息
        String key = "student_" + numberCode;
        Boolean hasKey = redisTemplate.hasKey(key);

        ValueOperations operations = redisTemplate.opsForValue();
        // 緩存存在
        if (hasKey) {
            String str = (String) operations.get(key);
            Student student = new Gson().fromJson(str, Student.class);
            System.out.println("StudentServiceImpl.getStudent() : 從緩存取得數據 >> " + student.toString());
            return student;
        }
        Student student = studentMapper.getStudent(numberCode);
        String str = new Gson().toJson(student);
        // 插入緩存中
        operations.set(key, str, 10, TimeUnit.SECONDS);
        System.out.println("StudentServiceImpl.getStudent() : 學生信息插入緩存 >> " + student.toString());
        return student;
    }

    @Override
    public int delete(String numberCode) {

        String key = "student_" + numberCode;
        Boolean hasKey = redisTemplate.hasKey(key);

        int delete = studentMapper.delete(numberCode);
        if( delete > 0){
            // 緩存存在,進行刪除
            if (hasKey) {
                redisTemplate.delete(key);
                System.out.println("StudentServiceImpl.update() : 從緩存中刪除編號學生 >> " + numberCode);
            }
        }
        return delete;
    }

    /**
     * 更新學生信息邏輯:
     * 如果緩存存在,刪除
     * 如果緩存不存在,不操作
     */
    @Override
    public int update(Student student) {

        String key = "student_" + student.getNumbercode();
        Boolean hasKey = redisTemplate.hasKey(key);

        int update = studentMapper.update(student);

        if( update > 0 ){
            // 緩存存在,進行刪除
            if (hasKey) {
                redisTemplate.delete(key);
                System.out.println("StudentServiceImpl.update() : 從緩存中刪除學生 >> " + student.toString());
            }

        }
        return update;
    }

    @Override
    public int insert(Student student) {

        String key = "student_list";

        int insert = studentMapper.insert(student);
        if (insert > 0) {
            redisTemplate.delete(key);
        }
        return insert;
    }
}
View Code
controller 層 StudentController.java
package com.example.demo.controller;

import com.example.demo.model.Student;
import com.example.demo.service.StudentService;
import com.google.gson.Gson;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(path = "/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping( path = "/getList")
    public List<Student> getList(){
        List<Student> students = studentService.selectAll();
        return students;
    }

    @GetMapping( path = "/getStudent")
    public String getList(@Param("numberCode") String numberCode){
        Student students = studentService.getStudent(numberCode);
        String str = new Gson().toJson(students);
        return str;
    }

    @PostMapping(path = "/insert")
    public String insert(@RequestBody Student student){
        int insert = studentService.insert(student);
        String msg = "";
        if( insert > 0 ){
            msg = "{\"msg\":\"新增成功\",\"flag\":true}";
        }else {
            msg = "{\"msg\":\"新增失敗\",\"flag\":false}";
        }
        return msg;
    }

    @GetMapping(path = "/delete")
    public String delete(@Param("numberCode") String numberCode){
        int delete = studentService.delete(numberCode);
        String msg = "";
        if( delete > 0 ){
            msg = "{\"msg\":\"刪除成功!!\",\"flag\":true}";
        }else {
            msg = "{\"msg\":\"刪除失敗!!\",\"flag\":false}";
        }
        return msg;
    }

    @PostMapping(path = "/update")
    public String update(@RequestBody Student student){
        int update = studentService.update(student);
        String msg = "";
        if( update > 0 ){
            msg = "{\"msg\":\"更新成功!!!\",\"flag\":true}";
        }else {
            msg = "{\"msg\":\"更新失敗!!!\",\"flag\":false}";
        }
        return msg;
    }

}
View Code

 

完整項目地址:https://github.com/oukele/SpringBoot-MyBatis-MySQL-Redis

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM