本地安装 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 +
'}';
}
}
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);
}
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);

}

 

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;
}
}
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;
} }

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

SpringBoot + MySQL + MyBatis 整合 Redis 实现缓存操作的更多相关文章

  1. mybatis整合redis二级缓存

    mybatis默认开启了二级缓存功能,在mybatis主配置文件中,将cacheEnabled设置成false,则会关闭二级缓存功能 <settings> <!--二级缓存默认开启, ...

  2. Spring Boot 整合 Redis 实现缓存操作

    摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢!   『 产品没有价值,开发团队再优秀也无济于事 – <启示录> 』   本文提纲 ...

  3. SpringBoot+Shiro+mybatis整合实战

    SpringBoot+Shiro+mybatis整合 1. 使用Springboot版本2.0.4 与shiro的版本 引入springboot和shiro依赖 <?xml version=&q ...

  4. 30分钟带你了解Springboot与Mybatis整合最佳实践

    前言:Springboot怎么使用想必也无需我多言,Mybitas作为实用性极强的ORM框架也深受广大开发人员喜爱,有关如何整合它们的文章在网络上随处可见.但是今天我会从实战的角度出发,谈谈我对二者结 ...

  5. springBoot+mysql+mybatis demo [基本配置] [遇到的问题]

    springBoot+mysql+mybatis的基本配置: 多环境 application.properties spring.profiles.active=dev spring.applicat ...

  6. Spring-Boot项目中配置redis注解缓存

    Spring-Boot项目中配置redis注解缓存 在pom中添加redis缓存支持依赖 <dependency> <groupId>org.springframework.b ...

  7. SpringBoot与Mybatis整合方式01(源码分析)

    前言:入职新公司,SpringBoot和Mybatis都被封装了一次,光用而不知道原理实在受不了,于是开始恶补源码,由于刚开始比较浅,存属娱乐,大神勿喷. 就如网上的流传的SpringBoot与Myb ...

  8. 项目总结10:通过反射解决springboot环境下从redis取缓存进行转换时出现ClassCastException异常问题

    通过反射解决springboot环境下从redis取缓存进行转换时出现ClassCastException异常问题 关键字 springboot热部署  ClassCastException异常 反射 ...

  9. springBoot整合redis(作缓存)

    springBoot整合Redis 1,配置Redis配置类 package org.redislearn.configuration; import java.lang.reflect.Method ...

随机推荐

  1. CentOS7.5下安装nginx --项目部署

    1.安装ngnix一些依赖包 [root@VM_39_157_centos ~]# yum -y install gcc gcc-c++ openssl-devel pcre-devel httpd- ...

  2. 内网环境下搭建maven私服小技巧

    背景 最近接手一个其他公司的项目,因为工程中使用了maven,而且里面有很多他们自己封装很多自己的构件(就是jar.war等等),需要将他们maven私服迁移到我们的私服上去,因为网络环境不通,所以不 ...

  3. php使用ffmpeg获取上传的视频的时长,码率等信息

    视频上传是程序员在很多时候需要用到的操作,然而上传完视频肯定要获得一些视频的详细信息,php本身是不支持信息获取的 ,所以采用ffmpeg第三方插件 首先你需要下载ffmpeg文件:官网地址:http ...

  4. Python习题006

    作业一:打印10*10  星星 ★☆ 要求一:普通打印★ l = 0 while l <10: h = 0 while h < 9: print("★", end=&q ...

  5. Python之字符与编码笔记

    概述 类型 str 字符串 bytes 字节 bytearray 字节数组 字符串编码架构 字符集:赋值一个编码到某个字符,以便在内存中表示 编码 Ecoding:转换字符到原始字节形式 解码 Dec ...

  6. 2019版UI学习路线(含大纲+视频+工具+网盘+面试题)

    2019最新UI设计师教程(学习路线+课程大纲+视频教程+面试题+学习工具) 什么是全链路UI设计 UI设计师是随着网络而兴起的新兴设计行业,从事对软件的人机交互.操作逻辑.界面美观的整体设计工作.涉 ...

  7. go 函数闭包

    Go 函数可以是闭包的.闭包是一个函数值,它来自函数体的外部的变量引用. 函数可以对这个引用值进行访问和赋值:换句话说这个函数被“绑定”在这个变量上. 例如,函数 adder 返回一个闭包.每个闭包都 ...

  8. odoo——日历的一对多与多对一

    # model文件 # -*- coding: utf-8 -*- from odoo import api, fields, models class TodoTestYear(models.Mod ...

  9. shell习题第21题:计算数字的个数

    [题目要求] 计算文档a.txt中每一行出现数字的个数并且要计算一下整个文档中一共出现了几个数字 例如a.txt如下: sdhhyh776dbbgbfg dhhdffhhhs556644382 运行结 ...

  10. Linux 编译kernel有关Kconfig文件详解

    ref : https://blog.csdn.net/Ultraman_hs/article/details/52984929 Kconfig的格式 下面截取/drivers/net下的Kconfi ...