SpringBoot集成Redis缓存数据

QingchenJia Lv3

一、引言

Redis是目前使用最为广泛的非关系型数据库,常用于Web项目中缓存数据。在访问量非常高的项目中,用户每与系统进行交互都将伴随后端对数据库的操作,通常其中最多的操作类型为查询,大量的访问数据库可能会导致数据库不堪重负。因此,使用Redis来缓存查询结果数据成了一个良好的解决方案,在首次查询时将查询结果缓存至Redis数据库中,下次查询同样的数据即从缓存中提取数据并返回。当数据库中的原始数据发生改变时,清楚Redis缓存,以保证数据同步。

二、步骤

1.安装Redis数据库

由于Redis官方团队仅针对Linux系统进行了开发,受限于设备而不得不使用Windows操作系统可以选择下载由Microsoft Archive团队开发的Windows版本,项目访问地址为https://github.com/microsoftarchive/redis

下载项目Release发布中合适版本后,解压文件内容如下。双击运行redis-server.exe文件即可启动Redis服务,启动前请注意6379端口的占用情况。然后可通过运行redis-cli.exeRedis客户端程序,进行数据库操作。

2.导入相关依赖

根据SpringBoot版本的不同,在Maven依赖中已对Redis这种常用依赖做好了依赖适配,因此在具体pom.xml文件中无需填写对应version

1
2
3
4
5
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>3.3.5</version>
</dependency>

3.GUI工具使用

推荐一款界面风格简洁,交互使用流畅的Redis数据库GUI工具——AnotherRedisDesktopManager。从名字能够看出,已经存在一款名为RedisDesktopManager的同类工具,务必注意名称,不要找错工具。

项目的访问地址为https://github.com/qishibo/AnotherRedisDesktopManager,仍然通过Release发布下载安装包,一路默认选择即可快速完成安装。

4.编写项目配置文件

Redis服务端安装在Windows本机上,主机配置127.0.0.1localhost,端口默认为6379

1
2
3
4
5
6
spring:
data:
redis:
host: 127.0.0.1
port: 6379
password:

5.书写测试代码

RedisTemplate类的对象由Spring框架进行Bean管理,在项目启动执行的过程中,自动注入。

1
2
3
4
5
6
7
8
9
10
11
@SpringBootTest
class ApplicationTests {
@Autowired
private RedisTemplate redisTemplate;

@Test
void testRedisUse() {
redisTemplate.opsForValue().set("name", "eric");
System.out.println(value.get("name"));
}
}

6.自定义RedisTemplate对象

使用SpringBoot框架默认提供的RedisTemplate对象Bean时,在存储key时会将字符串序列化,使得Redis中存储的key前面多上一串难以阅读的序列化字符,妨碍对缓存数据的查看,同时影响数据库中key的模糊匹配。

因此,需要自定义RedisTemplate对象Bean来解决,设置key的序列化方式为字符串序列化,这样以字符串作为key存入Redis数据库过程中进行序列化后,将不会出现难以理解的序列化字符前缀。

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
@Configuration
public class RedisConfig {
/**
* 配置RedisTemplate以支持Spring应用中的Redis操作
* 此方法主要负责初始化RedisTemplate,并设置其连接工厂和序列化方式
*
* @param redisCommandFactory Redis连接工厂,用于创建与Redis服务器的连接
* @return 配置完成的RedisTemplate实例,可用于执行Redis操作
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisCommandFactory) {
// 创建RedisTemplate实例
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

// 设置Redis连接工厂
redisTemplate.setConnectionFactory(redisCommandFactory);

// 设置键的序列化方式为字符串序列化
redisTemplate.setKeySerializer(RedisSerializer.string());
// 设置哈希键的序列化方式为字符串序列化
redisTemplate.setHashKeySerializer(RedisSerializer.string());

// 返回配置完成的RedisTemplate实例
return redisTemplate;
}
}

三、写在最后

使用Redis来进行缓存数据的存取已经成了大多数项目的公认选择,除了缓存数据库中的查询数据以外,手机短信验证码的定时过期也可以通过Redis来实现。此外,适合自己的GUI工具也能够帮助开发者更有效的进行开发和学习。

  • Title: SpringBoot集成Redis缓存数据
  • Author: QingchenJia
  • Created at : 2024-11-26 19:49:56
  • Updated at : 2026-05-13 12:45:18
  • Link: https://qingchenjia.github.io/2024/11/26/SpringBoot集成Redis缓存数据/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
SpringBoot集成Redis缓存数据