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

 

posted @ 2019-08-20 00:30  追梦滴小蜗牛  阅读(4174)  评论(0编辑  收藏  举报