从零搭建SpringBoot2.X整合Redis框架的详细教程
本篇文章给大家分享《从零搭建SpringBoot2.X整合Redis框架的详细教程》,覆盖了数据库的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。
最近也不知道写啥,看之前写过Kafka整合Springboot的文章,大家反响还挺热烈的,嘿嘿嘿,就感觉帮助到大家了还挺好的,也算是达到了自己的目的,正好,今天业务模块是springboot整合redis,因为之前做过,所以有现成的代码,cv一下之后就可以了,所以时间比较多,那就给大家整理一下Springboot整合Redis的代码实现吧,从项目搭建到源码实现,下面全都有,耐心看完,相信会对你有所帮助的
好了,话不多说,我们开始吧,同样的,还是建议能够自己在自己的PC端实现一下
个人公众号:Java架构师联盟,每日更新技术好文
一、使用Spring Initializr创建项目web项目
1、File→New→Project

2、点击Next如图所示,命名好Group和Artifact

3、Next后如图所示,勾选中需要的依赖,Spring Initializr会自动导入所需的starter

4、创建项目成功后,pom.xml文件中的依赖如下
4.0.0 org.springframework.boot spring-boot-starter-parent 2.2.2.RELEASE com.heny spring-boot-redis 0.0.1-SNAPSHOT spring-boot-redis Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-web org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.1 mysql mysql-connector-java runtime org.springframework.boot spring-boot-starter-test test org.junit.vintage junit-vintage-engine org.springframework.boot spring-boot-maven-plugin
5、在pom.xml文件中添加redis的starter
org.springframework.boot spring-boot-starter-data-redis
6、创建JavaBean用于封装数据库数据,需要实现Serializable
package com.henya.springboot.bean;
import java.io.Serializable;
public class Employee implements Serializable{
private Integer id;
private String lastName;
private String email;
private Integer gender; //性别 1男 0女
private Integer dId;
public Employee() {
super();
}
public Employee(Integer id, String lastName, String email, Integer gender, Integer dId) {
super();
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
this.dId = dId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Integer getdId() {
return dId;
}
public void setdId(Integer dId) {
this.dId = dId;
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + ", dId="
+ dId + "]";
}
}
注意:
在写JavaBean对象时需要实现Serializable接口否则会报以下错误:
Cannot deserialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException
7、整合Mybatis操作数据库,在application.properties配置文件中配置数据源信息
#serverTimezone用于指定时区,不然会报错 spring.datasource.url=jdbc:mysql://localhost:3306/cache?serverTimezone=UTC spring.datasource.username=root spring.datasource.password=123456 # 开启驼峰命名法规则 mybatis.configuration.map-underscore-to-camel-case=true #日志级别 logging.level.com.henya.springboot.mapper=debug
8、使用注解版Mybatis创建Mapper
package com.henya.springboot.mapper;
import com.henya.springboot.bean.Employee;
import org.apache.ibatis.annotations.*;
@Mapper
public interface EmployeeMapper {
@Select("SELECT * FROM employee WHERE id=#{id}")
public Employee getEmpById(Integer id);
@Update("UPDATE employee SET lastName=#{lastName},email=#{email},gender=#{gender},d_id=#{dId} WHERE id=#{id}")
public void updateEmp(Employee employee);
@Delete("DELETE FROM emlpoyee WHERE id=#{id}")
public void delEmpById(Integer id);
@Insert("INSERT INTO employee(lastName, email, gender, d_id) VALUES (#{lastName}, #{email}, #{gender}, #{dId})")
public Employee insertEmp(Employee employee);
@Select("SELECT * FROM employee WHERE lastName=#{lastName}")
public Employee getEmpByLastName(String lastName);
}
注意:
需要使用使用@MapperScan注解扫描Mapper所在的接口,只需要加在主程序类上即可。除此之外,还要使用@EnableCaching用于开启缓存。
@MapperScan("com.henya.springboot.mapper")
@SpringBootApplication
@EnableCaching //开启缓存
public class SpringBootRedisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootRedisApplication.class, args);
}
}
9、编写Service类,用于访问数据库或redis缓存
package com.henya.springboot.service;
import com.henya.springboot.bean.Employee;
import com.henya.springboot.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;
@CacheConfig(cacheNames = "emp") //抽取缓存的公共配置
@Service
public class EmployeeService {
@Autowired
EmployeeMapper employeeMapper;
/**
* @param id
* @return
*/
@Cacheable(cacheNames = {"emp"},keyGenerator = "myKeyGenerator")
public Employee getEmpById(Integer id) {
System.err.println("开始查询"+ id +"号员工");
Employee employee = employeeMapper.getEmpById(id);
return employee;
}
/**
* @CachePut:既调用方法(这个方法必须要执行),又更新缓存数据
* @param employee
* @return
*/
@CachePut(value = "emp",key = "#result.id")
public Employee updateEmp(Employee employee){
System.err.println("开始更新" + employee.getId() + "号员工");
employeeMapper.updateEmp(employee);
return employee;
}
/**
* @CacheEvict:缓存清除
* @param id
*/
@CacheEvict(value = "emp",beforeInvocation = true)
public void deleteEmp(Integer id){
System.err.println("删除" + id + "员工");
int i = 10/0;
}
10、编写Controller类
package com.henya.springboot.controller;
import com.henya.springboot.bean.Employee;
import com.henya.springboot.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description:
* @Author:HenYa
* @CreatTime:2019/12/1 12:44
*/
@RestController
public class EmployeeController {
@Autowired
EmployeeService employeeService;
@GetMapping("/emp/{id}")
public Employee getEmpById(@PathVariable("id") Integer id){
Employee employee = employeeService.getEmpById(id);
return employee;
}
@GetMapping("/emp")
public Employee updateEmp(Employee employee){
Employee emp = employeeService.updateEmp(employee);
return emp;
}
}
二、测试SpringBoot整合Redis是否成功
1、在浏览器访问,也可以使用测试类,笔者使用了浏览器访问http://localhost:8080/emp/1进行测试,初次访问时,控制台会提示开始查询1号员工,如图所示。

2、再次访问时,控制台并没有sql日志,如图所示。

3、此时使用RedisDesktopManager工具查看redis时有数据,并且cacheName为emp,如图所示

只是emp对象被序列化了。查看源码可知Redis默认使用Jdk进行序列化。
static RedisSerializer
查看RedisSerializer接口的实现有以下几种:

我们常用的就是以json的格式进行序列化。但是需要自定义RedisCacheManager。
三、自定义RedisCacheManager
package com.henya.springboot.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
/**
* @Description:
* @Author:HenYa
* @CreatTime:2019/12/6 20:50
*/
@Configuration
public class MyRedisConfig {
@Bean
public RedisCacheManager empCacheManager(RedisConnectionFactory redisConnectionFactory){
//RedisCacheManager redisCacheManager = new RedisCacheManager(redisConnectionFactory);
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
RedisSerializer
此时,Redis中缓存数据就以Json的格式进行序列化,如图所示。

今天关于《从零搭建SpringBoot2.X整合Redis框架的详细教程》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
Redis 缓存实现存储和读取历史搜索关键字的操作方法
- 上一篇
- Redis 缓存实现存储和读取历史搜索关键字的操作方法
- 下一篇
- 基于Redis位图实现系统用户登录统计
-
- 聪慧的战斗机
- 这篇博文真是及时雨啊,太细致了,写的不错,码起来,关注老哥了!希望老哥能多写数据库相关的文章。
- 2023-01-04 23:14:55
-
- 数据库 · Redis | 1天前 |
- Redis ZSET 实现延迟队列的分数设计
- 394浏览 收藏
-
- 数据库 · Redis | 2天前 | 事务 · redis集群 · redis 原子操作 Redis Cluster Hash Tag 多 key
- Redis Cluster Hash Tag 组织多 key 原子操作
- 357浏览 收藏
-
- 数据库 · Redis | 2天前 | 消息队列 · redis 消费者组 XAUTOCLAIM Redis Streams pending消息
- Redis 消费者组 pending 消息的认领与恢复流程
- 101浏览 收藏
-
- 数据库 · Redis | 2天前 |
- Redis Streams 按业务时间裁剪历史消息的参数方案
- 145浏览 收藏
-
- 数据库 · Redis | 2天前 | Redis · redis 地理位置 GEOSEARCHSTORE
- Redis GEOSEARCHSTORE 怎么保存附近对象结果
- 351浏览 收藏
-
- 数据库 · Redis | 2天前 |
- Redis BLMOVE 怎么实现可恢复的阻塞队列
- 460浏览 收藏
-
- 数据库 · Redis | 2天前 |
- Redis BITFIELD 溢出策略 WRAP SAT FAIL 怎么选
- 471浏览 收藏
-
- 数据库 · Redis | 2天前 |
- Redis SET 的 GET 选项怎么原子取得旧值
- 413浏览 收藏
-
- 数据库 · Redis | 3天前 | Redis ·
- Redis 分片 Pub/Sub 与普通 Pub/Sub 有什么区别
- 327浏览 收藏
-
- 数据库 · Redis | 3天前 |
- Redis LATENCY DOCTOR 怎么判断延迟来源
- 169浏览 收藏
-
- 数据库 · Redis | 3天前 |
- Redis ACL 怎么同时限制命令和键前缀
- 244浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 279次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 333次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 326次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 297次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 116次使用
-
- Redis Stream XTRIM 如何避免消费组积压无限增长
- 2026-09-12 501浏览
-
- Redis AOF rewrite 期间如何判断磁盘与内存压力
- 2026-09-12 501浏览
-
- Redis RDB 和 AOF 怎么按可接受数据丢失量选择
- 2026-09-08 501浏览
-
- Redis XAUTOCLAIM 之后为什么仍有 pending:JUSTID、PEL 与消息删除边界
- 2026-08-29 501浏览
-
- Redis SET 的 GET 与 KEEPTTL 怎么一起验收:旧值返回、续期与回滚边界
- 2026-08-20 501浏览
