来源:素文宅博客
地址:https://blog.yoodb.com/yoodb/article/detail/1570
Redis(Remote Dictionary Server ),即远程字典服务,是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。
Redis是一个高性能的key-value内存数据库,通常被称为数据结构服务器,因为值可以是字符串、哈希、列表、集合和有序集合等类型,在如今系统不断追求高并发、高效率的大环境下,Redis被广泛使用。
本文在前一篇“Spring Boot从入门到精通(四)连接MySQL数据库(附源码)”文章中的项目源码基础上(关注“Java精选”微信公众号,切换至后台->聚合->开源项目,可以查看Spring Boot系列框架从入门到精通教程)。
通过查询MySQL数据库中表数据存储到Redis缓存中,之后再使用Redis查询数据返回参数呈现到浏览器上,利用Spring Boot框架集成Redis实现缓存机制,分享给大家参考和学习。
Maven项目pom.xml文件
在Spring Boot项目中pom.xml文件配置信息如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
|
MySQL数据库数据源类文件
创建名为DataSourceConfig的类,上一篇已经针对该内容详细介绍,在这里就不过多解释了,如果大家有什么不明白可以翻看以前记录【微信公众号“Java精选”,Spring Boot从入门到精通系列文章】,具体代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
|
Redis缓存类文件
创建RedisConfig配置类,具体代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
注:在添加RedisConfig配置时,因为连接redis需要RedisConnection和RedisConnectionFactory,RedisConnection是通过RedisConnectionFactory进行创建。
实体类文件
新增BootUser实体类文件,具体代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
|
新增mapper接口类文件
mapper接口类文件,具体代码如下:
1 2 3 4 5 6 |
|
新增mapper xml文件
在src/main/resources/mapper/(不存在文件加新建)创建BootUserMapper.xml文件,具体配置信息如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
application.properties文件
在application.properties文件中增加MySQL数据库连接配置和Redis缓存连接配置参数,参考信息如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
注:其中spring.redis.database参数的配置通常使用0即可,Redis在配置的时候可以设置数据库数量,默认为16个,可以理解为数据库的schema。
创建service类文件
新增文件名BootUserService类文件,具体代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
创建controller类文件
新增文件名BootUserController类文件,具体代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
mapper的接口、xml文件及实体文件、service层、controller层创建完成后,目录如图:
项目启动
项目启动后访问请求地址:
http://localhost:8080/myt/getUsers
通过浏览器访问输出如下信息:
1 |
|
Spring Boot从入门到精通(六)集成Redis实现缓存机制(项目源码springboot-study-demo04)地址:https://github.com/yoodb/springboot。到此讲完了,Spring Boot集成Redis实现缓存机制,实际上就这么简单。不过需要注意使用的时候遇到的坑。~~