本地安装 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.0modelVersion> <parent> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-parentartifactId> <version>2.1.7.RELEASEversion> <relativePath/> parent> <groupId>com.examplegroupId> <artifactId>demoartifactId> <version>0.0.1-SNAPSHOTversion> <packaging>warpackaging> <name>demoname> <description>Demo project for Spring Bootdescription> <properties> <java.version>1.8java.version> properties> <dependencies> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-webartifactId> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-tomcatartifactId> <scope>providedscope> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-testartifactId> <scope>testscope> dependency> <dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <version>5.1.46version> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-data-redisartifactId> <version>2.1.6.RELEASEversion> dependency> <dependency> <groupId>org.mybatis.spring.bootgroupId> <artifactId>mybatis-spring-boot-starterartifactId> <version>1.3.2version> dependency> <dependency> <groupId>com.google.code.gsongroupId> <artifactId>gsonartifactId> <version>2.8.5version> dependency> dependencies> <build> <plugins> <plugin> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-maven-pluginartifactId> plugin> <plugin> <groupId>org.mybatis.generatorgroupId> <artifactId>mybatis-generator-maven-pluginartifactId> <version>1.3.7version> <configuration> <configurationFile>${basedir}/src/main/resources/generatorConfig.xmlconfigurationFile> <overwrite>trueoverwrite> configuration> <dependencies> <dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <version>8.0.15version> 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 + '}'; } }
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") ListselectAll(); @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); }
service 层 StudentService.java
package com.example.demo.service; import com.example.demo.model.Student; import java.util.List; public interface StudentService { ListselectAll(); Student getStudent(String numberCode); int delete(String numberCode); int update(Student student); int insert(Student student); }
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 ListselectAll() { 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 >() {}.getType(); List
list = new Gson().fromJson(redisList,type); System.out.println("StudentServiceImpl.selectAll() : 从缓存取得数据,条数:" + list.size()); return list; } List 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; } }
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 ListgetList(){ List 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; } }
完整项目地址:https://github.com/oukele/SpringBoot-MyBatis-MySQL-Redis