先附上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.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zhaolei</groupId>
<artifactId>springboot-cache-redis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-cache-redis</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
yml配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/redisdemo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: root
redis:
#redis 服务器地址
host: 192.168.88.130
#端口号
port: 6379
#Redis数据库索引(默认为0)
database: 0
# Redis服务器连接密码(默认为空)
password:
mybatis:
# 为实体类起别名
type-aliases-package: com.zhaolei.students.pojo
# 扫描类路径下的所有xml
mapper-locations: classpath:mapper/*.xml
configuration:
# none不自动匹配 FULL全部匹配 PARTIAL默认值-
auto-mapping-behavior: full
# 开启驼峰命名
map-underscore-to-camel-case: true
logging:
level:
com.zhaolei.springbootcacheredis.mapper: debug
mapper层
package com.zhaolei.springbootcacheredis.mapper;
import com.zhaolei.springbootcacheredis.pojo.Student;
import org.apache.ibatis.annotations.*;
import java.util.List;
/**
* @author 15579
* 2019/6/10 20:22
* 文件说明:
*/
public interface StudentMapper {
/**
* 查询所有记录
* @return
*/
@Select("select * from student")
List<Student> findAll();
/**
* 根据编号查询记录
* @param id
* @return
*/
@Select("select * from student where id=#{id}")
Student findById(Integer id);
/**
* 新增记录
* @param student
* @return
*/
@Insert("INSERT INTO `jpademo`.`student`(`name`, `sex`, `gradeId`) VALUES (#{name},#{sex},#{gradeId})")
int addStudent(Student student);
/**
* 修改记录
* @param student
* @return
*/
@Update("UPDATE `jpademo`.`student` SET `name` = #{name}, `sex` = #{sex}, `gradeId` =#{gradeId} WHERE `id` = #{id}")
int updateStudent(Student student);
/**
* 删除记录
* @param id
* @return
*/
@Delete("DELETE FROM student where id=#{id}")
int deleteStudent(Integer id);
}
pojo 实体类
/*
* Welcome to use the TableGo Tools.
*
* http://vipbooks.iteye.com
* http://blog.csdn.net/vipbooks
* http://www.cnblogs.com/vipbooks
*
* Author:bianj
* Email:edinsker@163.com
* Version:5.8.8
*/
package com.zhaolei.springbootcacheredis.pojo;
/**
* student
*
* @author zhaolei
* @version 1.0.0 2019-06-10
*/
public class Student implements java.io.Serializable {
/** 版本号 */
private static final long serialVersionUID = -6087187925653606230L;
/** id */
private Integer id;
/** name */
private String name;
/** sex */
private String sex;
/** gradeId */
private Integer gradeId;
/**
* 获取id
*
* @return id
*/
public Integer getId() {
return this.id;
}
/**
* 设置id
*
* @param id
*/
public void setId(Integer id) {
this.id = id;
}
/**
* 获取name
*
* @return name
*/
public String getName() {
return this.name;
}
/**
* 设置name
*
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取sex
*
* @return sex
*/
public String getSex() {
return this.sex;
}
/**
* 设置sex
*
* @param sex
*/
public void setSex(String sex) {
this.sex = sex;
}
/**
* 获取gradeId
*
* @return gradeId
*/
public Integer getGradeId() {
return this.gradeId;
}
/**
* 设置gradeId
*
* @param gradeId
*/
public void setGradeId(Integer gradeId) {
this.gradeId = gradeId;
}
}
service层
package com.zhaolei.springbootcacheredis.service;
import com.zhaolei.springbootcacheredis.pojo.Student;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
/**
* @author 15579
* 2019/6/10 20:22
* 文件说明:
*/
public interface StudentService {
/**
* 新增记录
* @return
*/
List<Student> findAll();
/**
* 根据编号查询记录
* @param id
* @return
*/
Student findById(Integer id);
/**
* 新增记录
* @param student
* @return
*/
Student addStudent(Student student);
/**
* 修改记录
* @param student
* @return
*/
Student updateStudent(Student student);
/**
* 删除记录
* @param id
* @return
*/
void deleteStudent(Integer id);
}
impl层(redis缓存主要是在这里实现)
package com.zhaolei.springbootcacheredis.service.impl;
import com.zhaolei.springbootcacheredis.mapper.StudentMapper;
import com.zhaolei.springbootcacheredis.pojo.Student;
import com.zhaolei.springbootcacheredis.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @author 15579
* 2019/6/10 20:22
* 文件说明:
*/
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Autowired
private RedisTemplate redisTemplate;
/**
* 新增记录
* @return
*/
@Override
public List<Student> findAll() {
String key="students";
/**
* redisTemplate.opsForValue();//操作字符串
* redisTemplate.opsForHash();//操作hash
* redisTemplate.opsForList();//操作list
* redisTemplate.opsForSet(); //操作set
* redisTemplate.opsForZSet();//操作有序set
*/
ListOperations<String,Student> listOperations = redisTemplate.opsForList(); //操作list的对象
//判断redis中是否含有指定的key
if(redisTemplate.hasKey(key)){
// 0 -1 查询所有
return listOperations.range(key,0,-1);
}else {
//无此key则向redis中存储
List<Student> studentList = studentMapper.findAll();
listOperations.leftPushAll(key,studentList);
return studentList;
}
}
/**
* 根据编号查询记录
* @param id
* @return
*/
@Override
public Student findById(Integer id) {
String key="student_"+id;//生成唯一key
ValueOperations<String,Student> operations = redisTemplate.opsForValue();
//判断redis中是否有此key
if(redisTemplate.hasKey(key)){
Student student = operations.get(key); //获取key值
return student;
}else{
//无此key则向redis中存储
Student student=studentMapper.findById(id);
operations.set(key,student); //存储
return student;
}
}
/**
* 新增记录
* @param student
* @return
*/
@Override
public Student addStudent(Student student) {
studentMapper.addStudent(student);
//新增成功之后需要刷新redis缓存中的数据
String key="students";
ListOperations listOperations = redisTemplate.opsForList();//操作list的对象
List<Student> studentList = studentMapper.findAll();
//如果redis中存在此key值则需要清除
if(redisTemplate.hasKey(key)){
redisTemplate.delete(key);
}
//向redis中存储新的查询结果
listOperations.rightPushAll(key,studentList);
return student;
}
/**
* 修改记录
* @param student
* @return
*/
@Override
@Transactional
public Student updateStudent(Student student) {
String key="student_"+student.getId();//生成唯一key
studentMapper.updateStudent(student);
ValueOperations valueOperations = redisTemplate.opsForValue();
//修改redis中数据的值 不存在key值则会自动添加
valueOperations.set(key,student);
return student;
}
/**
* 删除记录
* @param id
* @return
*/
@Override
public void deleteStudent(Integer id) {
String key="student_"+id; //生成唯一key
int ss= studentMapper.deleteStudent(id);
System.out.println(ss);
//判断redis中是否包含此key值
if(redisTemplate.hasKey(key)){
//有则从redis中删除
redisTemplate.delete(key);
}
}
}
注意:
redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForHash();//操作hash
redisTemplate.opsForList();//操作list
redisTemplate.opsForSet(); //操作set
redisTemplate.opsForZSet();//操作有序set
controller层
package com.zhaolei.springbootcacheredis.controller;
import com.zhaolei.springbootcacheredis.pojo.Student;
import com.zhaolei.springbootcacheredis.service.StudentService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* @author 15579
* 2019/6/10 21:00
* 文件说明:
*/
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
//查询所有
@GetMapping("/students")
public Object findAll(){
return studentService.findAll();
}
//根据编号查询
@GetMapping("/findById/{id}")
public Object findById(@PathVariable("id") Integer id){
return studentService.findById(id);
}
//新增
@PostMapping("/students")
public Object addStudent(Student student){
return studentService.addStudent(student);
}
//修改
@PutMapping("/students")
public Object updateStudent(Student student){
return studentService.updateStudent(student);
}
//删除
@DeleteMapping("/students/{id}")
public Object deleteStudent(@PathVariable("id") Integer id){
try {
studentService.deleteStudent(id);
return 1;
}catch (Exception e){
return 0;
}
}
}
然后运行项目测试方式为第一次查询之后存入缓存中然后在执行查询观察控制台是否打印sql语句
没有打印就是缓存成功了!
然后去我们的远程连接工具查看缓存数据会发现如下乱码情况:
出现这种情况是因为redis自带的序列化配置问题,所以我们还需要在SpringBoot项目中添加一个配置类或者在项目的主入口添加一个@Bean元素修改Redis默认的序列化配置代码如下:
package com.zhaolei.springbootcacheredis.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import java.net.UnknownHostException;
/**
* @author 15579
* 2019/6/10 21:48
* 文件说明:
*/
//修改redis默认的序列化配置
@Configuration
public class RedisConfig {
//覆盖默认的自动配置
@Bean
public RedisTemplate<Object, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
//修改默认的序列化规则
//1.创建序列化规则对象
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
//2.更改默认的序列化规则
template.setDefaultSerializer(jackson2JsonRedisSerializer);
return template;
}
}
删除出现乱码的缓存数据在运行项目发现乱码问题完美解决!
最后附上几个学习redis几个比较好的学习网址
菜鸟教程:https://www.runoob.com/redis/redis-tutorial.html
几个好的博客网址:
springboot整合redis做缓存:https://blog.csdn.net/zhangcongyi420/article/details/82686702
SpringBoot+MyBatis+Mysql+redis:https://blog.csdn.net/qq_34350964/article/details/82415096
Springboot使用redis实现简单crud:https://blog.csdn.net/qq_38522268/article/details/87607482
Spring Boot 整合 Redis 实现缓存操作:https://www.cnblogs.com/Alandre/p/6713769.html