从零搭建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文件中的依赖如下
<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 https://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.2.2.RELEASE</version><relativepath></relativepath><!-- lookup parent from repository --></parent><groupid>com.heny</groupid><artifactid>spring-boot-redis</artifactid><version>0.0.1-SNAPSHOT</version><name>spring-boot-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-web</artifactid></dependency><dependency><groupid>org.mybatis.spring.boot</groupid><artifactid>mybatis-spring-boot-starter</artifactid><version>2.1.1</version></dependency><dependency><groupid>mysql</groupid><artifactid>mysql-connector-java</artifactid><scope>runtime</scope></dependency><dependency><groupid>org.springframework.boot</groupid><artifactid>spring-boot-starter-test</artifactid><scope>test</scope><exclusions><exclusion><groupid>org.junit.vintage</groupid><artifactid>junit-vintage-engine</artifactid></exclusion></exclusions></dependency></dependencies><build><plugins><plugin><groupid>org.springframework.boot</groupid><artifactid>spring-boot-maven-plugin</artifactid></plugin></plugins></build></project>
5、在pom.xml文件中添加redis的starter
<dependency><groupid>org.springframework.boot</groupid><artifactid>spring-boot-starter-data-redis</artifactid></dependency>
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<object> java(@Nullable ClassLoader classLoader) { return new JdkSerializationRedisSerializer(classLoader); }</object>
查看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<object> redisSerializer = new GenericJackson2JsonRedisSerializer(); RedisSerializationContext.SerializationPair<object> pair = RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer); RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair); // 默认会将CacheName作为key的前缀 return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration); } }</object></object>
此时,Redis中缓存数据就以Json的格式进行序列化,如图所示。
今天关于《从零搭建SpringBoot2.X整合Redis框架的详细教程》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

- 上一篇
- Redis 缓存实现存储和读取历史搜索关键字的操作方法

- 下一篇
- 基于Redis位图实现系统用户登录统计
-
- 聪慧的战斗机
- 这篇博文真是及时雨啊,太细致了,写的不错,码起来,关注老哥了!希望老哥能多写数据库相关的文章。
- 2023-01-04 23:14:55
-
- 数据库 · Redis | 10小时前 |
- Redis容器化部署指南与优化技巧
- 484浏览 收藏
-
- 数据库 · Redis | 10小时前 |
- Redis漏洞扫描与修复全攻略
- 466浏览 收藏
-
- 数据库 · Redis | 11小时前 |
- Redis性能调优:关键参数配置指南
- 493浏览 收藏
-
- 数据库 · Redis | 11小时前 |
- Redis有序集合实现排行榜全解析
- 267浏览 收藏
-
- 数据库 · Redis | 13小时前 |
- RedisHyperLogLog高效统计技巧
- 268浏览 收藏
-
- 数据库 · Redis | 14小时前 |
- Redis数据安全防护全攻略
- 171浏览 收藏
-
- 数据库 · Redis | 16小时前 |
- Redis与MongoDB缓存优化全攻略
- 368浏览 收藏
-
- 数据库 · Redis | 18小时前 |
- Redis安全配置:强密码与访问控制设置教程
- 179浏览 收藏
-
- 数据库 · Redis | 18小时前 |
- Redis有序集合实现排行榜全解析
- 284浏览 收藏
-
- 数据库 · Redis | 19小时前 |
- Redis内存不足解决方法大全
- 482浏览 收藏
-
- 数据库 · Redis | 19小时前 |
- Redis主从复制故障排查与修复
- 292浏览 收藏
-
- 数据库 · Redis | 20小时前 |
- Redis集群脑裂问题及解决方法
- 441浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 免费AI认证证书
- 科大讯飞AI大学堂推出免费大模型工程师认证,助力您掌握AI技能,提升职场竞争力。体系化学习,实战项目,权威认证,助您成为企业级大模型应用人才。
- 33次使用
-
- 茅茅虫AIGC检测
- 茅茅虫AIGC检测,湖南茅茅虫科技有限公司倾力打造,运用NLP技术精准识别AI生成文本,提供论文、专著等学术文本的AIGC检测服务。支持多种格式,生成可视化报告,保障您的学术诚信和内容质量。
- 161次使用
-
- 赛林匹克平台(Challympics)
- 探索赛林匹克平台Challympics,一个聚焦人工智能、算力算法、量子计算等前沿技术的赛事聚合平台。连接产学研用,助力科技创新与产业升级。
- 224次使用
-
- 笔格AIPPT
- SEO 笔格AIPPT是135编辑器推出的AI智能PPT制作平台,依托DeepSeek大模型,实现智能大纲生成、一键PPT生成、AI文字优化、图像生成等功能。免费试用,提升PPT制作效率,适用于商务演示、教育培训等多种场景。
- 181次使用
-
- 稿定PPT
- 告别PPT制作难题!稿定PPT提供海量模板、AI智能生成、在线协作,助您轻松制作专业演示文稿。职场办公、教育学习、企业服务全覆盖,降本增效,释放创意!
- 170次使用
-
- redis复制有可能碰到的问题汇总
- 2023-01-01 501浏览
-
- 使用lua+redis解决发多张券的并发问题
- 2023-01-27 501浏览
-
- Redis应用实例分享:社交媒体平台设计
- 2023-06-21 501浏览
-
- 使用Python和Redis构建日志分析系统:如何实时监控系统运行状况
- 2023-08-08 501浏览
-
- 如何利用Redis和Python实现消息队列功能
- 2023-08-16 501浏览